需要说明:java跟python在思维模式上并不一样,java利用接口以及多态可以实现很多抽象上的东西,而python不行,其实以下很多设计模式写法并不适用也没有必要,更多是为了对比和帮助理解这些设计模式,毕竟设计模式的核心是解耦。

1.单例模式

#-*- encoding=utf-8 -*-

class Singleton(object):
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)
return cls._instance a = Singleton()
b = Singleton()
print id(a)
print id(b)

2.模板模式

#coding:utf-8

class CaffeineBeverageWithHook(object):
def prepareRecipe(self):
self.boilWater()
self.brew()
self.pourInCup()
if self.customerWantsCondiments():
self.addCondiments() def brew(self):
print "start brew." def addCondiments(self):
pass def boilWater(self):
print "start boilWater." def pourInCup(self):
print "Pour into cup" def customerWantsCondiments(self):
return False class CoffeeWithHook(CaffeineBeverageWithHook):
def brew(self):
print "Dripping coffee through filter." def addCondiments(self):
print "Add Sugar and Milk." def customerWantsCondiments(self):
return True if __name__ == '__main__':
coffeeWithHook = CoffeeWithHook()
coffeeWithHook.prepareRecipe()

3.适配器模式

#coding: utf-8

class Target(object):
def request(self):
print "this is target.request method." class Adaptee(object):
def special_request(self):
print "this is Adaptee.special_request method." class Adapter(object):
def __init__(self):
self.special_req = Adaptee() def request(self):
self.special_req.special_request() if __name__ == '__main__':
adapter = Adapter()
adapter.request()

4.策略模式:在策略模式中遵循依赖倒置原则,使得策略在代码运行时生效

# -*- coding: utf-8 -*-

class IStrategy(object):
def doSomething(self):
return class ConcreteStrategy1(IStrategy):
def doSomething(self):
print "concreteStrategy 1" class ConcreteStrategy2(IStrategy):
def doSomething(self):
print "concreteStrategy 2" class Context(object):
def __init__(self, concreteStrategy):
self.strategy = concreteStrategy() def execute(self):
self.strategy.doSomething() if __name__ == '__main__':
print "-----exec concreteStrategy 1-----"
context = Context(ConcreteStrategy1)
context.execute() print "-----exec concreteStrategy 2-----"
context = Context(ConcreteStrategy2)
context.execute()

5.工厂模式

#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding("utf-8") class XMobile(object):
def __init__(self, factory):
self._factory = factory
def order_mobile(self, brand):
mobile = self._factory.create_mobile(brand)
mobile.special_design()
mobile.hardware()
mobile.software()
mobile.combine()
mobile.box() class MobileFactory(object):
def create_mobile(self, brand):
if brand == "Huawei":
mobile = HuaweiProductLine(brand)
elif brand == "Xiaomi":
mobile = XiaomiProductLine(brand)
elif brand == "Meizu":
mobile = MeizuProductLine(brand)
return mobile class MobileProductLine(object):
def __init__(self, brand):
self.brand = brand def hardware(self):
print "准备硬件" def software(self):
print "准备软件" def combine(self):
print "合并手机" def box(self):
print "封装手机" class HuaweiProductLine(MobileProductLine):
def __init__(self, brand):
super(HuaweiProductLine,self).__init__(brand) def special_design(self):
print "使用Haisi CPU" class XiaomiProductLine(MobileProductLine):
def __init__(self, brand):
super(XiaomiProductLine,self).__init__(brand) def special_design(self):
print "使用MIUI" class MeizuProductLine(MobileProductLine):
def __init__(self, brand):
super(MeizuProductLine,self).__init__(brand) def special_design(self):
print "使用Flyme" if __name__ == '__main__':
mobileFactory = MobileFactory()
xmobile = XMobile(mobileFactory)
xmobile.order_mobile("Huawei")

6.观察者模式

#coding:utf-8

class Subject(object):
def __init__(self):
self.obs_list = [] # observer对象 def addObserver(self, obs):
self.obs_list.append(obs) def delObserver(self, obs):
self.obs_list.pop(obs) def notifyObserver(self):
for obs in self.obs_list:
obs.update() def doSomething(self):
return class ConcreteSubject(Subject):
def __init__(self):
super(ConcreteSubject, self).__init__() def doSomething(self):
self.notifyObserver() class Observer(object):
def update(self):
return class ConcreteObserver1(Observer):
def update(self):
print "观察者1收到信息,并进行处理。" class ConcreteObserver2(Observer):
def update(self):
print "观察者2收到信息,并进行处理。" if __name__ == '__main__':
concreteSubject = ConcreteSubject()
concreteSubject.addObserver(ConcreteObserver1())
concreteSubject.addObserver(ConcreteObserver2())
concreteSubject.doSomething()

7.外观模式

外观模式是将一系列接口进行封装,使得外层调用更加方便,因此不作说明

to be continue...

[python]设计模式的更多相关文章

  1. python设计模式浅析

    今天简单聊聊python的设计模式,GOF设计模式(c++)和Head first design pattern(Java)是两本设计模式的经典,基本可以照搬在python上面,但是你会发现pytho ...

  2. Python设计模式 - UML - 对象图(Object Diagram)

    简介 对象图和类图的基本概念是类似的,可以看作类图在系统某一时刻的镜像,显示了该时刻系统中参与交互的各个对象以及它们之间的关系. 对象图的元素包括对象.链接.包,元素之间的关系和类图相似. 对象图建模 ...

  3. Python 设计模式之路

    备注:本套笔记内容来源于互联网,只做学习使用,如有侵权请联系本笔记作者. 资料内容 Python 设计模式之路(一)——设计模式 初识 Python 设计模式之路(二)——简单工厂.工厂.抽象工厂模式 ...

  4. 最全36种python设计模式

    设计模式(Design pattern)代表了最佳的实践,通常被有经验的面向对象的软件开发人员所采用.设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案.这些解决方案是众多软件开发人员经过 ...

  5. Python设计模式 - UML - 类图(Class Diagram)

    简介 类图是面向对象分析和设计的核心,用来描述系统各个模块中类与类之间.接口与接口之间.类与接口之间的关系,以及每个类的属性.操作等特性,一般在详细设计过程中实施. 类图本身就是现实世界的抽象,是对系 ...

  6. python——设计模式

    设计模式是什么? 设计模式是经过总结.优化的,对我们经常会碰到的一些编程问题的可重用解决方案.一个设计模式并不像一个类或一个库那样能够直接作用于我们的代码.反之,设计模式更为高级,它是一种必须在特定情 ...

  7. Python设计模式 - 总览(更新中...)

    最近打算重构部分python项目,有道是"工欲善其事,必先利其器",所以有必要梳理一下相关设计模式.每次回顾基本概念或底层实现时都会有一些新的收获,希望这次也不例外. 本系列打算先 ...

  8. python设计模式之门面模式

    一.结构型设计模式 门面模式与单例模式,工厂模式不同,它是一种结构型模式. 结构型模式描述如何将对象和类组合成更大的结构 结构型模式是一种能够简化设计工作的模式,它能找出更简单的方法来认识或表示实体之 ...

  9. python设计模式之工厂模式

    一.理解工厂模式 在面向对象编程中,术语“工厂”表示一个负责创建替他类型对象的类.通常情况下,作为一个工厂的类有一个对象以及与它关联的多个方法.客户端使用某些参数调用此方法,之后,工厂会据此创建所需类 ...

  10. python设计模式之内置装饰器使用(四)

    前言 python内部有许多内建装饰器,它们都有特别的功能,下面对其归纳一下. 系列文章 python设计模式之单例模式(一) python设计模式之常用创建模式总结(二) python设计模式之装饰 ...

随机推荐

  1. 2、C#核心编程结构

     本学习主要参考Andrew Troelsen的C#与.NET4高级程序设计,这小节主要述说以下几个东西: Hello World的Main方法: 利用VS2010新建一个控制台应用程序Hello W ...

  2. Java集合专题总结(1):HashMap 和 HashTable 源码学习和面试总结

    2017年的秋招彻底结束了,感觉Java上面的最常见的集合相关的问题就是hash--系列和一些常用并发集合和队列,堆等结合算法一起考察,不完全统计,本人经历:先后百度.唯品会.58同城.新浪微博.趣分 ...

  3. 【转】基于linux下的dm9000网卡移植全分析

    转自:http://blog.sina.com.cn/s/blog_6abf2c04010189ui.html DM9000可以直接与ISA总线相连,也可以与大多数CPU直接相连.Mini2440采用 ...

  4. [JavaEE笔记]Cookie

    引言 由于 Http 是一种无状态的协议,服务器单从网络连接上无从知道客户身份. 会话跟踪是 Web 程序中常用的技术,用来跟踪用户的整个会话.常用会话跟踪技术是 Cookie 与 Session. ...

  5. .NET 开源SqlServer ORM框架 SqlSugar 3.0 API

    3.1.x ,将作为3.X系统的最后一个版本,下面将会开发 全新的功能 更新列表:https://github.com/sunkaixuan/SqlSugar/releases 优点: SqlSuga ...

  6. 基于 HTML5 的 WebGL 技术构建 3D 场景(一)

    今天和大家分享的是 3D 系列之 3D 预定义模型. HT for Web 提供了多种基础类型供用户建模使用,不同于传统的 3D 建模方式,HT 的建模核心都是基于 API 的接口方式,通过 HT 预 ...

  7. 随机记录工作中常见的sql用法错误(一)

    没事开始写博客,留下以前工作中常用的笔记,内容不全或者需要补充的可以留言,我只写我常用的. 网上很多类似动软生成器的小工具,这类工具虽然在表关系复杂的时候没什么软用,但是在一些简单的表结构关系还是很方 ...

  8. [问答] Firemonkey 控件继承后无法显示(空白)

    提问:如下安装后的 TMyPanel 能在设计期时正常显示,但 TMyPanel2 在设计期时是白板,不能正常看到,为什么? TMyPanel = class(TPanel) end; TMyCust ...

  9. nginx php-fpm 输出php错误日志

    nginx是一个web服务器,因此nginx的access日志只有对访问页面的记录,不会有php 的 error log信息. nginx把对php的请求发给php-fpm fastcgi进程来处理, ...

  10. Workflow笔记1——工作流介绍

    什么是工作流? 工作流(Workflow),是对工作流程及其各操作步骤之间业务规则的抽象.概括.描述.BPM:是Business Process Management的英文字母缩写.即业务流程管理,是 ...