需要说明: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. 计算机程序的思维逻辑 (53) - 剖析Collections - 算法

    之前几节介绍了各种具体容器类和抽象容器类,上节我们提到,Java中有一个类Collections,提供了很多针对容器接口的通用功能,这些功能都是以静态方法的方式提供的. 都有哪些功能呢?大概可以分为两 ...

  2. SQL实用

    实用的SQL语句   行列互转 create table test(id int,name varchar(20),quarter int,profile int) insert into test  ...

  3. HTML5学习

    HTML5动画效果 http://www.html5tricks.com/30-more-html5-apps.html http://www.html5tricks.com/category/htm ...

  4. .net 用户控件ascx.cs注册js脚本代码无效果

    在.net web项目中碰到一个比较奇怪的问题,网上没找到解决方案,先自己mark一下 问题描述: 添加一个用户控件ascx,在后端.cs添加js注册脚本,执行后没有弹出框 注册脚本为: this.P ...

  5. iOS学习笔记——滚动视图(scrollView)

    滚动视图:在根视图中添加UIScrollViewDelegate协议,声明一些对象属性 @interface BoViewController : UIViewController<UIScro ...

  6. Java中的多线程你只要看这一篇就够了

    学习Java的同学注意了!!! 学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入Java学习交流群,群号码:279558494 我们一起学Java! 引 如果对什么是线程.什么是进程仍存有疑惑, ...

  7. 深入理解DOM节点类型第五篇——元素节点Element

    × 目录 [1]特征 [2]子节点 [3]特性操作[4]attributes 前面的话 元素节点Element非常常用,是DOM文档树的主要节点:元素节点是html标签元素的DOM化结果.元素节点主要 ...

  8. button自适应宽度 并根据屏幕宽自动换行排列

    这是一个封装好的类TagListView, 1. 只需要调用两个方法 设置宽度,间距,边距 并赋给它需要显示的字符串数组; 2. 遵循tagListView的协议, 并实现返回buttonView的方 ...

  9. ReactiveCocoa 冷热订阅(cold subscribe, hot subscribe)

    ReactiveCocoa支持两种订阅方式,一种是冷订阅,一种是热订阅. 热订阅的特点: 1.不管有没有消息订阅着,发送者总会把消息发出去. 2.不管订阅者是什么时候订阅的,发送者总是会把相同的消息发 ...

  10. ViewPager与PagerAdapter

    ViewPager是一个可以用来滑动内部View的组件,他有一个老搭档PagerAdapter,我们这次就来看看他们这两位拍档的本事. 我们要使用ViewPager与PagerAdapter结合 首先 ...