前面c++粗略學習過一次,忘記了,現在回想回想。
Github:https://github.com/faif/python-patterns
simple_factory.py
#!/usr/bin/env python# encoding: utf-8"""簡單工廠模式增加操作: 1. 增加對應子類 2. 修改工廠類"""class Operation(object): @PRoperty def number_a(self): return self.__number_a @number_a.setter def number_a(self, value): self.__number_a = value @property def number_b(self): return self.__number_b @number_b.setter def number_b(self, value): self.__number_b = valueclass OperationAdd(Operation): def get_result(self): return self.number_a + self.number_bclass OperationSub(Operation): def get_result(self): return self.number_a - self.number_bclass OperationFactory(object): @staticmethod def create_operation(operate): if operate == "+": return OperationAdd() elif operate == "-": return OperationSub()if __name__ == '__main__': op = OperationFactory.create_operation('+') op.number_a = 10 op.number_b = 5 print op.get_result()abstract_factory.py#!/usr/bin/env python# encoding: utf-8"""抽象工廠模式提供一個創建一系列相關或相互依賴對象的接口, 而無需指定他們具體的類- 優點: 易于交換產品, 具體工廠配置不同的產品- 優點: 讓具體的創建實例過程與客戶端分離, 客戶端是通過它們的抽象接口操縱實例, 產品的具體類名也被具體工廠的實現分離, 不會出現在客戶端的代碼中"""from abc import ABCMeta, abstractmethodclass AbstractProductA(object): """ 抽象產品, 可能擁有多種實現 """ def __init__(self, name): self.name = name def __str__(self): return "ProductA: %s" % self.nameclass ConcreteProductA1(AbstractProductA): passclass ConcreteProductA2(AbstractProductA): passclass AbstractProductB(object): """ 抽象產品, 可能擁有多種實現 """ def __init__(self, name): self.name = name def __str__(self): return "ProductB: %s" % self.nameclass ConcreteProductB1(AbstractProductB): passclass ConcreteProductB2(AbstractProductB): passclass AbstractFactory(object): """ 抽象工廠接口, 包含所有產品創建的抽象方法 """ __metaclass__ = ABCMeta @abstractmethod def create_product_a(self): pass @abstractmethod def create_product_b(self): passclass ConcreteFactory1(AbstractFactory): """ 具體工廠, 創建具有特定實現的產品對象 """ def create_product_a(self): return ConcreteProductA1("PA1") def create_product_b(self): return ConcreteProductB1("PB1")class ConcreteFactory2(AbstractFactory): def create_product_a(self): return ConcreteProductA2("PA2") def create_product_b(self): return ConcreteProductB2("PB2")if __name__ == '__main__': factory = ConcreteFactory2() product_a = factory.create_product_a() print product_abuilder.py#!/usr/bin/env python# encoding: utf-8"""建造者模式將一個復雜對象的構建與它的表示分離, 使得同樣的構建過程可以創建不同的表示- 用戶只需指定需要建造的類型, 不需要知道具體地建造過程和細節- 建造者模式是在當創建復雜對象的算法應該獨立于該對象的組成部分以及它們的裝配方式時適用的模式"""from abc import ABCMeta, abstractmethodclass Product(object): """ 具體產品 """ def __init__(self): self.__parts = [] def add(self, part): self.__parts.append(part) def show(self): print '-'.join(self.__parts)class Builder(object): """ 為創建一個product對象的各個部件指定的抽象接口 """ __metaclass__ = ABCMeta @abstractmethod def build_part_1(self): pass @abstractmethod def build_part_2(self): pass @abstractmethod def get_result(self): passclass BuilderA(Builder): def __init__(self): self.__product = Product() def build_part_1(self): self.__product.add("partA1") def build_part_2(self): self.__product.add("partA2") def get_result(self): return self.__productclass BuilderB(Builder): def __init__(self): self.__product = Product() def build_part_1(self): self.__product.add("partB1") def build_part_2(self): self.__product.add("partB2") def get_result(self): return self.__productclass Director(object): @staticmethod def construct(builder): builder.build_part_1() builder.build_part_2()if __name__ == '__main__': ba = BuilderA() bb = BuilderB() Director.construct(ba) product = ba.get_result() product.show() Director.construct(bb) product = bb.get_result() product.show()factory_method.py#!/usr/bin/env python# encoding: utf-8"""工廠方法定義一個用于創建對象的接口, 讓子類決定實例化哪個類工廠方法使一個類的實例化延遲到其子類如果存在變更, 改creator即可"""from abc import ABCMeta, abstractmethodclass Product(object): """ 定義工廠方法所創建的對象接口 """ __metaclass__ = ABCMeta @abstractmethod def echo(self): passclass ConcreteProductA(Product): """ 具體的產品, 實現了product的接口 """ def echo(self): print "product A"class ConcreteProductB(Product): """ 具體的產品, 實現了product的接口 """ def echo(self): print "product B"class Creator(object): """ 聲明了工廠方法, 該方法返回一個Product類型的對象 """ __metaclass__ = ABCMeta @abstractmethod def create(self): passclass ConcreteCreatorA(Creator): """ 重定義, 返回一個ConcreteProduct實例 """ def create(self): return ConcreteProductA()class ConcreteCreatorB(Creator): def create(self): return ConcreteProductB()if __name__ == '__main__': factory_a = ConcreteCreatorA() product = factory_a.create() product.echo() factory_b = ConcreteCreatorB() product = factory_b.create() product.echo()prototype.py#!/usr/bin/env python# encoding: utf-8"""原型模式用原型實例指定創建對象的種類, 并且通過拷貝這些原型創建新的對象- 原型模型其實是從一個對象再創建另外一個可定制的對象, 而且不需要知道任何創建細節- 一般在初始化信息不發生變化的情況下, 克隆是最好的辦法, 既隱藏了對象創建的細節, 有提高了性能"""import copyfrom abc import ABCMeta, abstractmethodclass Prototype(object): """ 原型類, 聲明一個克隆自身的接口 """ __metaclass__ = ABCMeta def __init__(self, id): self.__id = id @property def id(self): return self.__id @id.setter def id(self, value): self.__id = value @abstractmethod def clone(self): passclass ConcretePrototypeA(Prototype): """ 具體原型類, 實現一個克隆自身的操作 """ def clone(self): # 淺拷貝 return copy.copy(self)class ConcretePrototypeB(Prototype): """ 具體原型類, 實現一個克隆自身的操作 """ def clone(self): return copy.copy(self)if __name__ == '__main__': ca = ConcretePrototypeA(1) c2 = ca.clone() print c2.idsingleton.py#!/usr/bin/env python# encoding: utf-8"""單例模式保證一個類僅有一個實例, 并提供一個訪問他的全局訪問點TODO: 如果是多線程, 要考慮加鎖"""class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, ** kwargs) return cls._instances[cls]#Python2class MyClass(object): __metaclass__ = Singletonif __name__ == '__main__': a = MyClass() b = MyClass() print a == b print a is b
新聞熱點
疑難解答