摘录自

http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html

一、简单工厂模式

模式特点:工厂根据条件产生不同功能的类。

程序实例:四则运算计算器,根据用户的输入产生相应的运算类,用这个运算类处理具体的运算。

代码特点:C/C++中的switch...case...分支使用字典的方式代替。

     使用异常机制对除数为0的情况进行处理。

Python代码  
  1. class Operation:
  2. def GetResult(self):
  3. pass
  4. class OperationAdd(Operation):
  5. def GetResult(self):
  6. return self.op1 + self.op2
  7. class OperationSub(Operation):
  8. def GetResult(self):
  9. return self.op1 - self.op2
  10. class OperationMul(Operation):
  11. def GetResult(self):
  12. return self.op1 * self.op2
  13. class OperationDiv(Operation):
  14. def GetResult(self):
  15. try:
  16. result = self.op1 / self.op2
  17. return result
  18. except:
  19. print "error:divided by zero."
  20. return 0
  21. class OperationUndef(Operation):
  22. def GetResult(self):
  23. print "Undefine operation."
  24. return 0
  25. class OperationFactory:
  26. operation = {}
  27. operation["+"] = OperationAdd();
  28. operation["-"] = OperationSub();
  29. operation["*"] = OperationMul();
  30. operation["/"] = OperationDiv();
  31. def createOperation(self, ch):
  32. if ch in self.operation:
  33. op = self.operation[ch]
  34. else:
  35. op = OperationUndef()
  36. return op
  37. if __name__ == "__main__":
  38. op = raw_input("operator: ")
  39. opa = input("a: ")
  40. opb = input("b: ")
  41. factory = OperationFactory()
  42. cal = factory.createOperation(op)
  43. cal.op1 = opa
  44. cal.op2 = opb
  45. print cal.GetResult()

二、策略模式

模式特点:定义算法家族并且分别封装,它们之间可以相互替换而不影响客户端。

程序实例:商场收银软件,需要根据不同的销售策略方式进行收费

代码特点:不同于同例1,这里使用字典是为了避免关键字不在字典导致bug的陷阱。

Python代码  
  1. class CashSuper:
  2. def AcceptCash(self, money):
  3. return 0
  4. class CashNormal(CashSuper):
  5. def AcceptCash(self, money):
  6. return money
  7. class CashRebate(CashSuper):
  8. discount = 0
  9. def __init__(self, ds):
  10. self.discount = ds
  11. def AcceptCash(self, money):
  12. return money * self.discount
  13. class CashReturn(CashSuper):
  14. total = 0;
  15. ret = 0;
  16. def __init__(self, t, r):
  17. self.total = t
  18. self.ret = r
  19. def AcceptCash(self, money):
  20. if (money >= self.total):
  21. return money - self.ret
  22. else:
  23. return money
  24. class CashContext:
  25. def __init__(self, csuper):
  26. self.cs = csuper
  27. def GetResult(self, money):
  28. return self.cs.AcceptCash(money)
  29. if __name__ == "__main__":
  30. money = input("money:")
  31. strategy = {}
  32. strategy[1] = CashContext(CashNormal())
  33. strategy[2] = CashContext(CashRebate(0.8))
  34. strategy[3] = CashContext(CashReturn(300, 100))
  35. ctype = input("type:[1]for normal,[2]for 80% discount [3]for 300 -100.")
  36. if ctype in strategy:
  37. cc = strategy[ctype]
  38. else:
  39. print "Undefine type.Use normal mode."
  40. cc = strategy[1]
  41. print "you will pay:%d" % (cc.GetResult(money))

三、装饰模式

模式特点:动态地为对象增加额外的职责

程序实例:展示一个人一件一件穿衣服的过程。

代码特点:无

Python代码 
  1. class Person:
  2. def __init__(self, tname):
  3. self.name = tname
  4. def Show(self):
  5. print "dressed %s" % (self.name)
  6. class Finery(Person):
  7. componet = None
  8. def __init__(self):
  9. pass
  10. def Decorate(self, ct):
  11. self.componet = ct
  12. def Show(self):
  13. if (self.componet != None):
  14. self.componet.Show()
  15. class TShirts(Finery):
  16. def __init__(self):
  17. pass
  18. def Show(self):
  19. print "Big T-shirt "
  20. self.componet.Show()
  21. class BigTrouser(Finery):
  22. def __init__(self):
  23. pass
  24. def Show(self):
  25. print "Big Trouser "
  26. self.componet.Show()
  27. if __name__ == "__main__":
  28. p = Person("somebody")
  29. bt = BigTrouser()
  30. ts = TShirts()
  31. bt.Decorate(p)
  32. ts.Decorate(bt)
  33. ts.Show()

四、代理模式

模式特点:为其他对象提供一种代理以控制对这个对象的访问。

程序实例:同模式特点描述。

代码特点:无

Python代码  
  1. class Interface :
  2. def Request(self):
  3. return 0
  4. class RealSubject(Interface):
  5. def Request(self):
  6. print "Real request."
  7. class Proxy(Interface):
  8. def Request(self):
  9. self.real = RealSubject()
  10. self.real.Request()
  11. if __name__ == "__main__":
  12. p = Proxy()
  13. p.Request()

五、工厂方法模式

模式特点:定义一个用于创建对象的接口,让子类决定实例化哪一个类。这使得一个类的实例化延迟到其子类。

程序实例:基类雷锋类,派生出学生类和志愿者类,由这两种子类完成“学雷锋”工作。子类的创建由雷锋工厂的对应的子类完成。

代码特点:无

Python代码  
  1. class LeiFeng:
  2. def Sweep(self):
  3. print "LeiFeng sweep"
  4. class Student(LeiFeng):
  5. def Sweep(self):
  6. print "Student sweep"
  7. class Volenter(LeiFeng):
  8. def Sweep(self):
  9. print "Volenter sweep"
  10. class LeiFengFactory:
  11. def CreateLeiFeng(self):
  12. temp = LeiFeng()
  13. return temp
  14. class StudentFactory(LeiFengFactory):
  15. def CreateLeiFeng(self):
  16. temp = Student()
  17. return temp
  18. class VolenterFactory(LeiFengFactory):
  19. def CreateLeiFeng(self):
  20. temp = Volenter()
  21. return temp
  22. if __name__ == "__main__":
  23. sf = StudentFactory()
  24. s = sf.CreateLeiFeng()
  25. s.Sweep()
  26. sdf = VolenterFactory()
  27. sd = sdf.CreateLeiFeng()
  28. sd.Sweep()

六、原型模式

模式特点:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

程序实例:从简历原型,生成新的简历

代码特点:简历类Resume提供的Clone()方法其实并不是真正的Clone,只是为已存在对象增加了一次引用。

     Python为对象提供的copy模块中的copy方法和deepcopy方法已经实现了原型模式,但由于例子的层次较浅,二者看不出区别。

    

import copy

class WorkExp:place=""year=0class Resume:name = ''age = 0def __init__(self,n):self.name = ndef SetAge(self,a):self.age = adef SetWorkExp(self,p,y):self.place = pself.year = ydef Display(self):print self.ageprint self.placeprint self.yeardef Clone(self):#实际不是“克隆”,只是返回了自身return selfif __name__ == "__main__":a = Resume("a")b = a.Clone()c = copy.copy(a)d = copy.deepcopy(a)a.SetAge(7)b.SetAge(12)c.SetAge(15)d.SetAge(18)a.SetWorkExp("PrimarySchool",1996)b.SetWorkExp("MidSchool",2001)c.SetWorkExp("HighSchool",2004)d.SetWorkExp("University",2007)a.Display()b.Display()c.Display()d.Display()

七、模板方法模式

模式特点:定义一个操作中的算法骨架,将一些步骤延迟至子类中。

程序实例:考试时使用同一种考卷(父类),不同学生上交自己填写的试卷(子类方法的实现)

代码特点:无

Python代码 
  1. class Paper:
  2. def Question1(self):
  3. print "1:A. B. C. D."
  4. print "(%s)" % self.Answer1()
  5. def Question2(self):
  6. print "1:A. B. C. D."
  7. print "(%s)" % self.Answer2()
  8. def Answer1(self):
  9. return ""
  10. def Answer2(self):
  11. return ""
  12. class PaperA(Paper):
  13. def Answer1(self):
  14. return "B"
  15. def Answer2(self):
  16. return "C";
  17. class PaperB(Paper):
  18. def Answer1(self):
  19. return "D"
  20. def Answer2(self):
  21. return "D";
  22. if __name__ == "__main__":
  23. s1 = PaperA()
  24. s2 = PaperB()
  25. print "student 1"
  26. s1.Question1()
  27. s1.Question2()
  28. print "student 2"
  29. s2.Question1()
  30. s2.Question2()

八、外观模式

模式特点:为一组调用提供一致的接口。

程序实例:接口将几种调用分别组合成为两组,用户通过接口调用其中的一组。

代码特点:无

class SubSystemOne:def MethodOne(self):print "SubSysOne"class SubSystemTwo:def MethodTwo(self):print "SubSysTwo"class SubSystemThree:def MethodThree(self):print "SubSysThree"class SubSystemFour:def MethodFour(self):print "SubSysFour"class Facade:def __init__(self):self.one = SubSystemOne()self.two = SubSystemTwo()self.three = SubSystemThree()self.four = SubSystemFour()def MethodA(self):print "MethodA"self.one.MethodOne()self.two.MethodTwo()self.four.MethodFour()def MethodB(self):print "MethodB"self.two.MethodTwo()self.three.MethodThree()if __name__ == "__main__":facade = Facade()facade.MethodA()facade.MethodB()

九、建造者模式

模式特点:将一个复杂对象的构建(Director)与它的表示(Builder)分离,使得同样的构建过程可以创建不同的表示(ConcreteBuilder)。

程序实例:“画”出一个四肢健全(头身手腿)的小人

代码特点:无

Python代码 
  1. class Person:
  2. def CreateHead(self):
  3. pass
  4. def CreateHand(self):
  5. pass
  6. def CreateBody(self):
  7. pass
  8. def CreateFoot(self):
  9. pass
  10. class ThinPerson(Person):
  11. def CreateHead(self):
  12. print "thin head"
  13. def CreateHand(self):
  14. print "thin hand"
  15. def CreateBody(self):
  16. print "thin body"
  17. def CreateFoot(self):
  18. print "thin foot"
  19. class ThickPerson(Person):
  20. def CreateHead(self):
  21. print "thick head"
  22. def CreateHand(self):
  23. print "thick hand"
  24. def CreateBody(self):
  25. print "thick body"
  26. def CreateFoot(self):
  27. print "thick foot"
  28. class Director:
  29. def __init__(self, temp):
  30. self.p = temp
  31. def Create(self):
  32. self.p.CreateHead()
  33. self.p.CreateBody()
  34. self.p.CreateHand()
  35. self.p.CreateFoot()
  36. if __name__ == "__main__":
  37. p = ThickPerson()
  38. d = Director(p)
  39. d.Create()

十、观察者模式

模式特点:定义了一种一对多的关系,让多个观察对象同时监听一个主题对象,当主题对象状态发生变化时会通知所有观察者。

程序实例:公司里有两种上班时趁老板不在时偷懒的员工:看NBA的和看股票行情的,并且事先让老板秘书当老板出现时通知他们继续做手头上的工作。

程序特点:无

Python代码
  1. class Observer:
  2. def __init__(self, strname, strsub):
  3. self.name = strname
  4. self.sub = strsub
  5. def Update(self):
  6. pass
  7. class StockObserver(Observer):
  8. #no need to rewrite __init__()
  9. def Update(self):
  10. print "%s:%s,stop watching Stock and go on work!" % (self.name, self.sub.action)
  11. class NBAObserver(Observer):
  12. def Update(self):
  13. print "%s:%s,stop watching NBA and go on work!" % (self.name, self.sub.action)
  14. class SecretaryBase:
  15. def __init__(self):
  16. self.observers = []
  17. def Attach(self, new_observer):
  18. pass
  19. def Notify(self):
  20. pass
  21. class Secretary(SecretaryBase):
  22. def Attach(self, new_observer):
  23. self.observers.append(new_observer)
  24. def Notify(self):
  25. for p in self.observers:
  26. p.Update()
  27. if __name__ == "__main__":
  28. p = Secretary()
  29. s1 = StockObserver("xh", p)
  30. s2 = NBAObserver("wyt", p)
  31. p.Attach(s1);
  32. p.Attach(s2);
  33. p.action = "WARNING:BOSS ";
  34. p.Notify()

十一、抽象工厂模式

模式特点:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们的类。

程序实例:提供对不同的数据库访问的支持。

     IUser和IDepartment是两种不同的抽象产品,它们都有Access和SQL Server这两种不同的实现;IFactory是产生IUser和IDepartment的抽象工厂,根据具体实现(AccessFactory和SqlFactory)产生对应的具体的对象(CAccessUser与CAccessDepartment,或者CSqlUser与CSqlDepartment)。

代码特点:无

Python代码
  1. class IUser:
  2. def GetUser(self):
  3. pass
  4. def InsertUser(self):
  5. pass
  6. class IDepartment:
  7. def GetDepartment(self):
  8. pass
  9. def InsertDepartment(self):
  10. pass
  11. class CAccessUser(IUser):
  12. def GetUser(self):
  13. print "Access GetUser"
  14. def InsertUser(self):
  15. print "Access InsertUser"
  16. class CAccessDepartment(IDepartment):
  17. def GetDepartment(self):
  18. print "Access GetDepartment"
  19. def InsertDepartment(self):
  20. print "Access InsertDepartment"
  21. class CSqlUser(IUser):
  22. def GetUser(self):
  23. print "Sql GetUser"
  24. def InsertUser(self):
  25. print "Sql InsertUser"
  26. class CSqlDepartment(IDepartment):
  27. def GetDepartment(self):
  28. print "Sql GetDepartment"
  29. def InsertDepartment(self):
  30. print "Sql InsertDepartment"
  31. class IFactory:
  32. def CreateUser(self):
  33. pass
  34. def CreateDepartment(self):
  35. pass
  36. class AccessFactory(IFactory):
  37. def CreateUser(self):
  38. temp = CAccessUser()
  39. return temp
  40. def CreateDepartment(self):
  41. temp = CAccessDepartment()
  42. return temp
  43. class SqlFactory(IFactory):
  44. def CreateUser(self):
  45. temp = CSqlUser()
  46. return temp
  47. def CreateDepartment(self):
  48. temp = CSqlDepartment()
  49. return temp
  50. if __name__ == "__main__":
  51. factory = SqlFactory()
  52. user = factory.CreateUser()
  53. depart = factory.CreateDepartment()
  54. user.GetUser()
  55. depart.GetDepartment()

十二、状态模式

模式特点:当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。

程序实例:描述一个程序员的工作状态,当需要改变状态时发生改变,不同状态下的方法实现不同

代码特点:无

Python代码
  1. class State:
  2. def WirteProgram(self):
  3. pass
  4. class Work:
  5. def __init__(self):
  6. self.hour = 9
  7. self.current = ForenoonState()
  8. def SetState(self, temp):
  9. self.current = temp
  10. def WriteProgram(self):
  11. self.current.WriteProgram(self)
  12. class NoonState(State):
  13. def WriteProgram(self, w):
  14. print "noon working"
  15. if (w.hour < 13):
  16. print "fun."
  17. else:
  18. print "need to rest."
  19. class ForenoonState(State):
  20. def WriteProgram(self, w):
  21. if (w.hour < 12):
  22. print "morning working"
  23. print "energetic"
  24. else:
  25. w.SetState(NoonState())
  26. w.WriteProgram()
  27. if __name__ == "__main__":
  28. mywork = Work()
  29. mywork.hour = 9
  30. mywork.WriteProgram()
  31. mywork.hour = 14
  32. mywork.WriteProgram()

十三、适配器模式

模式特点:将一个类的接口转换成为客户希望的另外一个接口。

程序实例:用户通过适配器使用一个类的方法。

代码特点:无

class Target:def Request():print "common request."class Adaptee(Target):def SpecificRequest(self):print "specific request."class Adapter(Target):def __init__(self,ada):self.adaptee = adadef Request(self):self.adaptee.SpecificRequest()if __name__ == "__main__":adaptee = Adaptee()adapter = Adapter(adaptee)adapter.Request()

十四、备忘录模式

模式特点:在不破坏封装性的前提下捕获一个对象的内部状态,并在该对象之外保存这个状态,以后可以将对象恢复到这个状态。

程序实例:将Originator对象的状态封装成Memo对象保存在Caretaker内

代码特点:无

class Originator:def __init__(self):self.state = ""def Show(self):print self.statedef CreateMemo(self):return Memo(self.state)def SetMemo(self,memo):self.state = memo.stateclass Memo:state= ""def __init__(self,ts):self.state = tsclass Caretaker:memo = ""if __name__ == "__main__":on = Originator()on.state = "on"on.Show()c = Caretaker()c.memo=on.CreateMemo()on.state="off"on.Show()on.SetMemo(c.memo)on.Show()

十五、组合模式

模式特点:将对象组合成成树形结构以表示“部分-整体”的层次结构

程序实例:公司人员的组织结构

代码特点:无

class Component:def __init__(self,strName):self.m_strName = strNamedef Add(self,com):passdef Display(self,nDepth):passclass Leaf(Component):def Add(self,com):print "leaf can't add"def Display(self,nDepth):strtemp = ""for i in range(nDepth):strtemp=strtemp+"-"strtemp=strtemp+self.m_strNameprint strtempclass Composite(Component):def __init__(self,strName):self.m_strName = strNameself.c = []def Add(self,com):self.c.append(com)def Display(self,nDepth):strtemp=""for i in range(nDepth):strtemp=strtemp+"-"strtemp=strtemp+self.m_strNameprint strtempfor com in self.c:com.Display(nDepth+2)if __name__ == "__main__":p = Composite("Wong")p.Add(Leaf("Lee"))p.Add(Leaf("Zhao"))p1 = Composite("Wu")p1.Add(Leaf("San"))p.Add(p1)p.Display(1);

十六、迭代器模式

模式特点:提供方法顺序访问一个聚合对象中各元素,而又不暴露该对象的内部表示

说明:这个模式没有写代码实现,原因是使用Python的列表和for ... in list就能够完成不同类型对象聚合的迭代功能了。

十七、单例模式

模式特点:保证类仅有一个实例,并提供一个访问它的全局访问点。

说明:     为了实现单例模式费了不少工夫,后来查到一篇博文对此有很详细的介绍,而且实现方式也很丰富,通过对代码的学习可以了解更多Python的用法。以下的代码出自GhostFromHeaven的专栏,地址:http://blog.csdn.net/ghostfromheaven/article/details/7671853。不过正如其作者在Python单例模式终极版所说:

我要问的是,Python真的需要单例模式吗?我指像其他编程语言中的单例模式。

答案是:不需要!

因为,Python有模块(module),最pythonic的单例典范。

模块在在一个应用程序中只有一份,它本身就是单例的,将你所需要的属性和方法,直接暴露在模块中变成模块的全局变量和方法即可!

#-*- encoding=utf-8 -*-
print '----------------------方法1--------------------------'
#方法1,实现__new__方法
#并在将一个类的实例绑定到类变量_instance上,
#如果cls._instance为None说明该类还没有实例化过,实例化该类,并返回
#如果cls._instance不为None,直接返回cls._instance
class Singleton(object):def __new__(cls, *args, **kw):if not hasattr(cls, '_instance'):orig = super(Singleton, cls)cls._instance = orig.__new__(cls, *args, **kw)return cls._instanceclass MyClass(Singleton):a = 1one = MyClass()
two = MyClass()two.a = 3
print one.a
#3
#one和two完全相同,可以用id(), ==, is检测
print id(one)
#29097904
print id(two)
#29097904
print one == two
#True
print one is two
#Trueprint '----------------------方法2--------------------------'
#方法2,共享属性;所谓单例就是所有引用(实例、对象)拥有相同的状态(属性)和行为(方法)
#同一个类的所有实例天然拥有相同的行为(方法),
#只需要保证同一个类的所有实例具有相同的状态(属性)即可
#所有实例共享属性的最简单最直接的方法就是__dict__属性指向(引用)同一个字典(dict)
#可参看:http://code.activestate.com/recipes/66531/
class Borg(object):_state = {}def __new__(cls, *args, **kw):ob = super(Borg, cls).__new__(cls, *args, **kw)ob.__dict__ = cls._statereturn obclass MyClass2(Borg):a = 1one = MyClass2()
two = MyClass2()#one和two是两个不同的对象,id, ==, is对比结果可看出
two.a = 3
print one.a
#3
print id(one)
#28873680
print id(two)
#28873712
print one == two
#False
print one is two
#False
#但是one和two具有相同的(同一个__dict__属性),见:
print id(one.__dict__)
#30104000
print id(two.__dict__)
#30104000print '----------------------方法3--------------------------'
#方法3:本质上是方法1的升级(或者说高级)版
#使用__metaclass__(元类)的高级python用法
class Singleton2(type):def __init__(cls, name, bases, dict):super(Singleton2, cls).__init__(name, bases, dict)cls._instance = Nonedef __call__(cls, *args, **kw):if cls._instance is None:cls._instance = super(Singleton2, cls).__call__(*args, **kw)return cls._instanceclass MyClass3(object):__metaclass__ = Singleton2one = MyClass3()
two = MyClass3()two.a = 3
print one.a
#3
print id(one)
#31495472
print id(two)
#31495472
print one == two
#True
print one is two
#Trueprint '----------------------方法4--------------------------'
#方法4:也是方法1的升级(高级)版本,
#使用装饰器(decorator),
#这是一种更pythonic,更elegant的方法,
#单例类本身根本不知道自己是单例的,因为他本身(自己的代码)并不是单例的
def singleton(cls, *args, **kw):instances = {}def _singleton():if cls not in instances:instances[cls] = cls(*args, **kw)return instances[cls]return _singleton@singleton
class MyClass4(object):a = 1def __init__(self, x=0):self.x = xone = MyClass4()
two = MyClass4()two.a = 3
print one.a
#3
print id(one)
#29660784
print id(two)
#29660784
print one == two
#True
print one is two
#True
one.x = 1
print one.x
#1
print two.x

十八、桥接模式

模式特点:将抽象部分与它的实现部分分离,使它们都可以独立地变化。

程序实例:两种品牌的手机,要求它们都可以运行游戏和通讯录两个软件,而不是为每个品牌的手机都独立编写不同的软件。

代码特点:虽然使用了object的新型类,不过在这里不是必须的,是对在Python2.2之后“尽量使用新型类”的建议的遵从示范。

class HandsetSoft(object):def Run(self):passclass HandsetGame(HandsetSoft):def Run(self):print "Game"class HandsetAddressList(HandsetSoft):def Run(self):print "Address List"class HandsetBrand(object):def __init__(self):self.m_soft = Nonedef SetHandsetSoft(self,temp):self.m_soft= tempdef Run(self):passclass HandsetBrandM(HandsetBrand):def Run(self):if not (self.m_soft == None):print "BrandM"self.m_soft.Run()class HandsetBrandN(HandsetBrand):def Run(self):if not (self.m_soft == None):print "BrandN"self.m_soft.Run()if __name__ == "__main__":brand = HandsetBrandM()brand.SetHandsetSoft(HandsetGame())brand.Run()brand.SetHandsetSoft(HandsetAddressList())brand.Run() 

十九、命令模式

模式特点:将请求封装成对象,从而使可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤消的操作。

程序实例:烧烤店有两种食物,羊肉串和鸡翅。客户向服务员点单,服务员将点好的单告诉大厨,由大厨进行烹饪。

代码特点:注意在遍历列表时不要用注释的方式删除,否则会出现bug。bug示例程序附在后面,我认为这是因为remove打乱了for迭代查询列表的顺序导致的。

class Barbucer:def MakeMutton(self):print "Mutton"def MakeChickenWing(self):print "Chicken Wing"class Command:def __init__(self,temp):self.receiver=tempdef ExecuteCmd(self):passclass BakeMuttonCmd(Command):def ExecuteCmd(self):self.receiver.MakeMutton()class ChickenWingCmd(Command):def ExecuteCmd(self):self.receiver.MakeChickenWing()class Waiter:def __init__(self):self.order =[]def SetCmd(self,command):self.order.append(command)print "Add Order"def Notify(self):for cmd in self.order:#self.order.remove(cmd)#lead to a bugcmd.ExecuteCmd()if __name__ == "__main__":barbucer=Barbucer()cmd=BakeMuttonCmd(barbucer)cmd2=ChickenWingCmd(barbucer)girl=Waiter()girl.SetCmd(cmd)girl.SetCmd(cmd2)girl.Notify()

在for中remove会导致bug的展示代码:

c=[0,1,2,3]
for i in c:print ic.remove(i)#output:
#0
#2

二十、职责链模式

模式特点:使多个对象都有机会处理请求,从而避免发送者和接收者的耦合关系。将对象连成链并沿着这条链传递请求直到被处理。

程序实例:请假和加薪等请求发给上级,如果上级无权决定,那么递交给上级的上级。

代码特点:无

Python代码  
  1. class Request:
  2. def __init__(self, tcontent, tnum):
  3. self.content = tcontent
  4. self.num = tnum
  5. class Manager:
  6. def __init__(self, temp):
  7. self.name = temp
  8. def SetSuccessor(self, temp):
  9. self.manager = temp
  10. def GetRequest(self, req):
  11. pass
  12. class CommonManager(Manager):
  13. def GetRequest(self, req):
  14. if (req.num >= 0 and req.num < 10):
  15. print "%s handled %d request." % (self.name, req.num)
  16. else:
  17. self.manager.GetRequest(req)
  18. class MajorDomo(Manager):
  19. def GetRequest(self, req):
  20. if (req.num >= 10):
  21. print "%s handled %d request." % (self.name, req.num)
  22. if __name__ == "__main__":
  23. common = CommonManager("Zhang")
  24. major = MajorDomo("Lee")
  25. common.SetSuccessor(major)
  26. req = Request("rest", 33)
  27. common.GetRequest(req)
  28. req2 = Request("salary", 3)
  29. common.GetRequest(req2)

二十一、中介者模式

模式特点:用一个对象来封装一系列的对象交互,中介者使各对象不需要显示地相互引用,从而使耦合松散,而且可以独立地改变它们之间的交互。

程序实例:两个对象通过中介者相互通信

代码特点:无

class Mediator:def Send(self,message,col):passclass Colleague:def __init__(self,temp):self.mediator = tempclass Colleague1(Colleague):def Send(self,message):self.mediator.Send(message,self)def Notify(self,message):print "Colleague1 get a message:%s" %messageclass Colleague2(Colleague):def Send(self,message):self.mediator.Send(message,self)def Notify(self,message):print "Colleague2 get a message:%s" %messageclass ConcreteMediator(Mediator):def Send(self,message,col):if(col==col1):col2.Notify(message)else:col1.Notify(message)if __name__ == "__main__":m =ConcreteMediator()col1 = Colleague1(m)col2 = Colleague1(m)m.col1=col1m.col2=col2col1.Send("How are you?");col2.Send("Fine.");

二十二、享元模式

模式特点:运用共享技术有效地支持大量细粒度的对象。

程序实例:一个网站工厂,根据用户请求的类别返回相应类别的网站。如果这种类别的网站已经在服务器上,那么返回这种网站并加上不同用户的独特的数据;如果没有,那么生成一个。

代码特点:为了展示每种网站的由用户请求的次数,这里为它们建立了一个引用次数的字典。

      之所以不用Python的sys模块中的sys.getrefcount()方法统计引用计数是因为有的对象可能在别处被隐式的引用,从而增加了引用计数。

import sysclass WebSite:def Use(self):passclass ConcreteWebSite(WebSite):def __init__(self,strName):self.name = strNamedef Use(self,user):print "Website type:%s,user:%s" %(self.name,user)class UnShareWebSite(WebSite):def __init__(self,strName):self.name = strNamedef Use(self,user):print "UnShare Website type:%s,user:%s" %(self.name, user)class WebFactory:def __init__(self):test = ConcreteWebSite("test")self.webtype ={"test":test}self.count = {"test":0}def GetWeb(self,webtype):if webtype not in self.webtype:temp = ConcreteWebSite(webtype)self.webtype[webtype] = tempself.count[webtype] =1else:temp = self.webtype[webtype]self.count[webtype] = self.count[webtype]+1return tempdef GetCount(self):for key in self.webtype:#print "type: %s, count:%d" %(key,sys.getrefcount(self.webtype[key]))print "type: %s, count:%d " %(key,self.count[key])if __name__ == "__main__":f = WebFactory()ws=f.GetWeb("blog")ws.Use("Lee")ws2=f.GetWeb("show")ws2.Use("Jack")ws3=f.GetWeb("blog")ws3.Use("Chen")ws4=UnShareWebSite("TEST")ws4.Use("Mr.Q")print f.webtypef.GetCount()

二十三、解释器模式

模式特点:给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。

程序实例:(只是模式特点的最简单示范)

代码特点:无

class Context:def __init__(self):self.input=""self.output=""class AbstractExpression:def Interpret(self,context):passclass Expression(AbstractExpression):def Interpret(self,context):print "terminal interpret"class NonterminalExpression(AbstractExpression):def Interpret(self,context):print "Nonterminal interpret"if __name__ == "__main__":context= ""c = []c = c + [Expression()]c = c + [NonterminalExpression()]c = c + [Expression()]c = c + [Expression()]for a in c:a.Interpret(context)

二十四、访问者模式

模式特点:表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。

程序实例:对于男人和女人(接受访问者的元素,ObjectStructure用于穷举这些元素),不同的遭遇(具体的访问者)引发两种对象的不同行为。

代码特点:无

# -*- coding: UTF-8 -*-
class Person:def Accept(self,visitor):passclass Man(Person):def Accept(self,visitor):visitor.GetManConclusion(self)class Woman(Person):def Accept(self,visitor):visitor.GetWomanConclusion(self)class Action:def GetManConclusion(self,concreteElementA):passdef GetWomanConclusion(self,concreteElementB):passclass Success(Action):def GetManConclusion(self,concreteElementA):print "男人成功时,背后有个伟大的女人"def GetWomanConclusion(self,concreteElementB):print "女人成功时,背后有个不成功的男人"class Failure(Action):def GetManConclusion(self,concreteElementA):print "男人失败时,闷头喝酒,谁也不用劝"def GetWomanConclusion(self,concreteElementB):print "女人失败时,眼泪汪汪,谁也劝不了"class ObjectStructure:def __init__(self):self.plist=[]def Add(self,p):self.plist=self.plist+[p]def Display(self,act):for p in self.plist:p.Accept(act)if __name__ == "__main__":os = ObjectStructure()os.Add(Man())os.Add(Woman())sc = Success()os.Display(sc)fl = Failure()os.Display(fl)

转载于:https://www.cnblogs.com/wangqingyi/articles/3863009.html

python为语言的设计模式相关推荐

  1. 《Python编程实战:运用设计模式、并发和程序库创建高质量程序》—— 第1章 Python的创建型设计模式...

    本节书摘来自华章出版社<Python编程实战:运用设计模式.并发和程序库创建高质量程序>一 书中的第1章,第1.1节,作者:(美) Mark Summerfield,更多章节内容可以访问云 ...

  2. Python之23种设计模式

    目录篇: python相关目录篇 点击跳转 目录 设计模式介绍 GoF该书设计了23个设计模式 设计模式(Design Patterns)--可复用面向对象软件的基础 设计模式分类 1 创建型模式 2 ...

  3. Python脚本语言写法

    Python脚本语言写法 脚本语言的开始行,是指文件中的代码用什么可执行程序去运行它,就这么简单. #!/usr/bin/python是告诉操作系统执行这个脚本的时候,调用/usr/bin下的pyth ...

  4. 各种编程语言功能综合简要介绍(C,C++,JAVA,PHP,PYTHON,易语言)

    各种编程语言功能综合简要介绍(C,C++,JAVA,PHP,PYTHON,易语言) 总结 a.一个语言或者一个东西能火是和这种语言进入某一子行业的契机有关.也就是说这个语言有没有解决社会急需的问题. ...

  5. 如何用Python一门语言通吃高性能并发、GPU计算和深度学习

    [CTO讲堂]如何用Python一门语言通吃高性能并发.GPU计算和深度学习 发表于2016-01-04 15:11| 4374次阅读| 来源CSDN| 4 条评论| 作者蒲婧 CTO俱乐部CTOCT ...

  6. python计算在月球的体重程序_# Python程序语言设计基础(第二版)程序练习题

    Python程序语言设计基础(第二版)程序练习题 3.1 重量计算,月球上物体的体重是在地球上的16.5%,假如你在地球上每年增长0.5kg,编写程序输出未来10年你在地球和月球上的体重状况. cur ...

  7. python实现多语言语种识别_用Python进行语言检测

    最近正好碰到这个需求,总结一下用Python进行语言检测的方法. 1.用unicode编码检测 汉字.韩文.日文等都有对应的unicode字符集范围,只要用正则表达式匹配出来即可. 在判断的时候,往往 ...

  8. go语言和python结合_Go+Python双语言混合开发-第1章 【阶段一:Go语言基础】

    1-1 Go+Python双语言混合开发-课程导学 (11:35) 1-2 课程资源获取方式 - 非常重要!!! (06:07) 1-3 课程中需要用到的开发环境介绍 (03:47) 1-4 wind ...

  9. python实验报告代写_TensorFlow作业代写、代做Python程序语言作业、代写github课程作业、Python实验作业代写...

    TensorFlow作业代写.代做Python程序语言作业.代写github课程作业.Python实验作业代写 日期:2019-07-10 10:34 Python Practical Examine ...

最新文章

  1. python函数返回多个变量_Python 3:通过多个函数返回变量
  2. SQL进阶随笔--case用法(一)
  3. springboot学习笔记(六)
  4. 用Qemu模拟vexpress-a9 (四) --- u-boot引导kernel,用nfs挂载根文件系统
  5. sharding-jdbc学习
  6. EE Servlet 3:如何在Web应用程序中设置后端服务
  7. 如何成为一个合格的算法工程师?这对你来说也许并不是很困难
  8. java 斗地主_java 斗地主
  9. Git——撤销和删除操作【git restore / git rm 】
  10. Linux学习笔记一:vmware安装Ubuntu虚拟机并进行联网设置
  11. Oracle OCP题库变了,052全新题库收集整理-30
  12. 步进电机怎么选型?步进电机驱动器选型要怎么选?
  13. 校园二手交易平台的简要分析(纯文档)
  14. SNAT、DNAT、MASQUERADE的区别
  15. 留学论文辅导计算机专业Essay写作范文
  16. 同步回调与异步回调的实现与学习
  17. 海康威视SDK二次开发通过云台参数设置控制摄像机的位置
  18. bugku ctf 妹子的陌陌 (想要妹子陌陌号吗? 做题来拿吧)
  19. 以太网,令牌网,FDDI,ATM是什么?有什么区别?
  20. Ctrl+Space冲突解决及输入法精简

热门文章

  1. 程序员的这108个笑话(下)你都看得懂吗?
  2. 马化腾发大招!又一批百万富翁诞生。。。
  3. java编程-集五福
  4. 爬取某小说榜单爬虫及可视化分析
  5. fontface_使用Fontface Ninja轻松检测字体
  6. html+css+js实现抽奖功能
  7. 读起来,微微心疼的句子
  8. UI非常漂亮的数诚1对1直播/带收徒/带公会/运营版本
  9. 【面试记录】云和恩墨一面
  10. ROS launch调用摄像头问题(已解决)