标签:
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()
标签:
原文地址:http://www.cnblogs.com/alexkn/p/5628612.html