[python]设计模式
需要说明: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]设计模式的更多相关文章
- python设计模式浅析
今天简单聊聊python的设计模式,GOF设计模式(c++)和Head first design pattern(Java)是两本设计模式的经典,基本可以照搬在python上面,但是你会发现pytho ...
- Python设计模式 - UML - 对象图(Object Diagram)
简介 对象图和类图的基本概念是类似的,可以看作类图在系统某一时刻的镜像,显示了该时刻系统中参与交互的各个对象以及它们之间的关系. 对象图的元素包括对象.链接.包,元素之间的关系和类图相似. 对象图建模 ...
- Python 设计模式之路
备注:本套笔记内容来源于互联网,只做学习使用,如有侵权请联系本笔记作者. 资料内容 Python 设计模式之路(一)——设计模式 初识 Python 设计模式之路(二)——简单工厂.工厂.抽象工厂模式 ...
- 最全36种python设计模式
设计模式(Design pattern)代表了最佳的实践,通常被有经验的面向对象的软件开发人员所采用.设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案.这些解决方案是众多软件开发人员经过 ...
- Python设计模式 - UML - 类图(Class Diagram)
简介 类图是面向对象分析和设计的核心,用来描述系统各个模块中类与类之间.接口与接口之间.类与接口之间的关系,以及每个类的属性.操作等特性,一般在详细设计过程中实施. 类图本身就是现实世界的抽象,是对系 ...
- python——设计模式
设计模式是什么? 设计模式是经过总结.优化的,对我们经常会碰到的一些编程问题的可重用解决方案.一个设计模式并不像一个类或一个库那样能够直接作用于我们的代码.反之,设计模式更为高级,它是一种必须在特定情 ...
- Python设计模式 - 总览(更新中...)
最近打算重构部分python项目,有道是"工欲善其事,必先利其器",所以有必要梳理一下相关设计模式.每次回顾基本概念或底层实现时都会有一些新的收获,希望这次也不例外. 本系列打算先 ...
- python设计模式之门面模式
一.结构型设计模式 门面模式与单例模式,工厂模式不同,它是一种结构型模式. 结构型模式描述如何将对象和类组合成更大的结构 结构型模式是一种能够简化设计工作的模式,它能找出更简单的方法来认识或表示实体之 ...
- python设计模式之工厂模式
一.理解工厂模式 在面向对象编程中,术语“工厂”表示一个负责创建替他类型对象的类.通常情况下,作为一个工厂的类有一个对象以及与它关联的多个方法.客户端使用某些参数调用此方法,之后,工厂会据此创建所需类 ...
- python设计模式之内置装饰器使用(四)
前言 python内部有许多内建装饰器,它们都有特别的功能,下面对其归纳一下. 系列文章 python设计模式之单例模式(一) python设计模式之常用创建模式总结(二) python设计模式之装饰 ...
随机推荐
- Oracle数据加载之sqlldr工具的介绍
环境: 服务端:RHEL6.4 + Oracle 11.2.0.4 客户端:WIN10 + Oracle 11.2.0.1 client 目录: sqlldr语法 sqlldr实验准备 sqlldr常 ...
- 匹夫细说C#:从园友留言到动手实现C#虚函数机制
前言 上一篇文章匹夫通过CIL代码简析了一下C#函数调用的话题.虽然点击进来的童鞋并不如匹夫预料的那么多,但也还是有一些挺有质量的来自园友的回复.这不,就有一个园友提出了这样一个代码,这段代码如果被编 ...
- Qt 拷贝文件目录
bool copyDir(const QString &source, const QString &destination, bool override) { QDir direct ...
- eclipse中Maven运行时报错: -Dmaven.multiModuleProjectDirectory system propery is not set. Check $M2_HOME environment variable and mvn script match.
1.安装 Maven 如果需要使用到 Maven ,必须首先安装 Maven , Maven 的下载地址在 Apache Maven 中有,您也可以点击这里下载 zip ,tar.gz. 下载好 Ma ...
- C#开发微信门户及应用(34)--微信裂变红包
在上篇随笔<C#开发微信门户及应用(33)--微信现金红包的封装及使用>介绍了普通现金红包的封装和使用,这种红包只能单独一次发给一个人,用户获取了红包就完成了,如果我们让用户收到红包后,可 ...
- spring事务概念理解
1.数据并发问题 脏读 A事务读取B事务尚未提交的更新数据,并在此数据的基础上操作.如果B事务回滚,则A事务读取的数据就是错误的.即读取了脏数据或者错误数据. 不可重复组 A事务先后读取了B事务提交[ ...
- JVM 架构解读
每个Java开发人员都知道字节码由JRE(Java运行时环境)执行.但许多人不知道JRE是Java Virtual Machine(JVM)的实现,它分析字节码,解释代码并执行它.作为开发人员,我们应 ...
- 解决ngnix服务器上的Discuz!x2.5 Upload Error:413错误
1.修改php.ini sudo nano /etc/php5/fpm/php.ini #打开php.ini找到并修改以下的参数,目的是修改上传限制 max_execution_time = 900 ...
- heartbeat在yum系发行版本的处理资料
centos 安装包[rpm]和光盘iso文件 http://mirror.centos.org/centos/ 对应如上包的代码 http://vault.centos.org/ git.cento ...
- css揭秘--笔记(未完)
第0章 关于本书 1, 本书要用到一个工具函数————$$(),它可以让我们更容易获取和遍历所有匹配特定css选择符的dom元素: function $$(selector,context){ con ...