需要说明: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. UWP开发之Mvvmlight实践五:SuspensionManager中断挂起以及复原处理

    最近比较忙有一段时间没有更新了,再接再厉继续分享. 案例下载:https://github.com/NewBLife/UWP/tree/master/SuspendSample 先我们看看App在生命 ...

  2. STemwin汉字显示

    硬件环境: STM32F429,电容屏800X480 5点触控RGB屏幕 ,SPI flash: 软件环境: UCOSIII,STemwin: 汉字显示方法: 1.在SPIflash中装在字库XBF_ ...

  3. Node学习笔记(一):stream流操作

    NodeJs中谈及较多的可能就是Stream模块了,先写一个简单的ajax回调 $.post("index.php",{data:'aaa',order:'ccc'},functi ...

  4. C# 复制指定节点的所有子孙节点到新建的节点下

    XML结构: 新建一个mask_list节点,一个procedure节点,将上面的mask_list和procedure节点的所有子孙节点添加到新建的mask_list和procedure节点 Xml ...

  5. PHP如何实现网址伪静态

    Apache的 mod_rewrite是比较强大的,在进行网站建设时,可以通过这个模块来实现伪静态. 主要步骤如下: 1.检测Apache是否开启mod_rewrite功能     可以通过php提供 ...

  6. wnmp环境搭建

    windows下配置nginx+php环境 刚看到nginx这个词,我很好奇它的读法(engine x),我的直译是“引擎x”,一般引“擎代”表了性能,而“x”大多出现是表示“xtras(额外的效果) ...

  7. 每天一个设计模式-3 适配器模式(Adapteer)

    每天一个设计模式-3 适配器模式(Adapteer) 1.现实中的情况 旧式电脑的硬盘是串口的,直接与硬盘连接,新硬盘是并口的,显然新硬盘不能直接连在电脑上,于是就有了转接线.好了,今天的学习主题出来 ...

  8. 使用Ring Buffer构建高性能的文件写入程序

    最近常收到SOD框架的朋友报告的SOD的SQL日志功能报错:文件句柄丢失.经过分析得知,这些朋友使用SOD框架开发了访问量比较大的系统,由于忘记关闭SQL日志功能所以出现了很高频率的日志写入操作,从而 ...

  9. SpringMVC的执行流程(二)

    文字解析: 1.客户端发出一个http请求给web服务器,web服务器对http请求进行解析,如果匹配 DispatcherServlet的请求映射路径(在web.xml中指定),web容器将请求转交 ...

  10. 超级小的web手势库AlloyFinger发布

    简介 针对多点触控设备编程的Web手势组件,快速帮助你的web程序增加手势支持,也不用再担心click 300ms的延迟了.拥有两个版本,无依赖的独立版和react版本.除了Dom对象,也可监听Can ...