繼續另一種類型。
adapter.py
#!/usr/bin/env python# encoding: utf-8"""適配器模式將一個類的接口轉換成客戶希望的另一個接口.使得原本由于接口不兼容而不能work的那些類可以work- 適用: 系統的數據和行為都正確, 但是接口不符時. (已存在, 但是其接口和需要的不同)- 主要用于, 希望復用一些現存的類, 但接口又與復用環境要求不一致的情況- 客戶代碼可以統一調用同一接口, 簡單直接緊湊"""from abc import ABCMeta, abstractmethodclass Target(object): """ 客戶鎖期待的接口, 目標可以使具體或抽象的類, 也可以是接口 """ __metaclass__ = ABCMeta @abstractmethod def request(self): passclass Adaptee(object): """ 需要適配的類 """ def special_request(self): PRint "I am special"class Adapter(Target): """ 適配器, 通過在內部包裝一個adapter對象, 把源接口轉換成目標接口 """ def __init__(self): self.adaptee = Adaptee() def request(self): self.adaptee.special_request()if __name__ == '__main__': a = Adapter() a.request()bridge.py#!/usr/bin/env python# encoding: utf-8"""橋接模式將抽象部分與它的實現部分分離, 使它們都可以獨立地變化- 獨立變化"""from abc import ABCMeta, abstractmethodclass Implementor(object): __metaclass__ = ABCMeta @abstractmethod def Operation(self): passclass ConcreteImplementorA(Implementor): def operation(self): print "plan A"class ConcreteImplementorB(Implementor): def operation(self): print "plan B"class Abstraction(object): def __init__(self, implementor=None): if implementor is not None: self.__implementor = implementor @property def implementor(self): return self.__implementor @implementor.setter def implementor(self, value): self.__implementor = value def operation(self): self.__implementor.operation()class RefinedAbstraction(Abstraction): passif __name__ == '__main__': ab = RefinedAbstraction() ab.implementor = ConcreteImplementorA() ab.operation() ab.implementor = ConcreteImplementorB() ab.operation()composite.py
#!/usr/bin/env python# encoding: utf-8"""組合模式將對象組合成樹狀結構以表示`部分-整體`的層次結構使得用戶對單個對象和組合對象的使用具有一致性- 適用: 需求中體現部分與整體層次的結構, 希望用戶可以忽略組合對象與單個對象的不同, 統一地使用組合結構中的所有對象時, 就應該考慮使用組合模式- 優點: 讓用戶可以一致性的使用組合結構和單個對象"""class Component(object): """ 組合中的對象聲明接口 在適當情況下, 實現所有類共有接口的默認行為 聲明接口用于訪問和管理Component的子部件 """ def __init__(self, name): self.name = name def add(self, component): pass def remove(self, component): pass def display(self, depth): passclass Leaf(Component): """ 組合中表示葉節點對象, 葉節點沒有子節點 """ def add(self, component): print "can not add to a leaf" def remove(self, component): print "can not remove from a leaf" def display(self, depth): print '-' * depth + self.nameclass Composite(Component): """ 定義有枝節點行為, 用于存儲子部件 實現相關操作 """ def __init__(self, name): super(Composite, self).__init__(name) self.__children = [] def add(self, component): self.__children.append(component) def remove(self, component): self.__children.remove(component) def display(self, depth): print '-' * depth + self.name for c in self.__children: c.display(depth + 2)if __name__ == '__main__': root = Composite("root") root.add(Leaf("A")) root.add(Leaf("B")) comp = Composite("X") comp.add(Leaf("XA")) comp.add(Leaf("XB")) root.add(comp) root.display(1)decorator.py#!/usr/bin/env python# encoding: utf-8"""裝飾模式動態地給一個對象添加一些額外的職責,就增加功能來說, 裝飾模式比生成子類更為靈活- 裝飾模式, 是為已有功能動態地添加更多功能的一種方式- 有效地將核心職責和裝飾功能區分開"""from abc import ABCMeta, abstractmethodclass Component(object): """ 定義一個對象接口 可以給這些對象動態地增加職責 """ __metaclass__ = ABCMeta @abstractmethod def operation(self): passclass ConcreteComponent(Component): """ 定義了一個具體對象, 也可以給這個對象增加職責 """ def operation(self): print "Hello world"class Decorator(Component): """ 裝飾抽象類, 繼承了component, 從外類來擴展component類的功能, 但對于component來說, 是無須知道decorator類的存在的 """ def __init__(self, component): self.__component = component def operation(self): if self.__component: self.__component.operation()class DecoratorA(Decorator): """ 具體裝飾對象, 給component添加職責 """ def operation(self): print "<h1>" super(DecoratorA, self).operation() print "</h1>"class DecoratorB(Decorator): def operation(self): print "<strong>" super(DecoratorB, self).operation() print "</strong>"if __name__ == '__main__': c = ConcreteComponent() d1 = DecoratorA(c) d1.operation() d2 = DecoratorB(d1) d2.operation()facade.py#!/usr/bin/env python# encoding: utf-8"""外觀模式(門面模式)為子系統中的一組接口提供一個一致的界面.定義了一個高層接口, 是的這一子系統更加容易使用- 統一接口人- 減少依賴"""class SystemA(object): def call_a(self): print "call a"class SystemB(object): def call_b(self): print "call b"class SystemC(object): def call_c(self): print "call c"class Facade(object): def __init__(self): self.sys_a = SystemA() self.sys_b = SystemB() self.sys_c = SystemC() def action_a(self): self.sys_a.call_a() self.sys_b.call_b() def action_b(self): self.sys_b.call_b() self.sys_c.call_c()if __name__ == '__main__': facade = Facade() facade.action_a()flyweight.py#!/usr/bin/env python# encoding: utf-8"""享元模式運用共享技術有效地支持大量細粒度的對象- 可以避免大量非常相似類的開銷- 把區分的參數放在類實例外面, 在方法調用時傳遞進去- 如果一個應用程序使用了大量對象, 而大量的這些對象造成了很大的存儲開銷時"""from abc import ABCMeta, abstractmethodclass Flyweight(object): """ 所有具體享元類的超類或接口 通過這個接口, flyweight可以接受并作用于外部狀態 """ __metaclass__ = ABCMeta @abstractmethod def operation(self, extrinsicstate): passclass ConcreteFlyweight(Flyweight): """ 繼承flyweight超類或實現flyweight接口, 并未內部狀態增加存儲空間 """ def operation(self, extrinsicstate): print "specific flyweight:", extrinsicstateclass UnsharedConcreteFlyweight(Flyweight): """ 不需要共享的flyweight子類 """ def operation(self, extrinsicstate): print "unshared flyweight:", extrinsicstateclass FlyweightFactory(object): """ 一個享元工廠, 用來創建并管理flyweight對象, 主要是用阿里確保合理地共享 flyweight 當用戶請求一個flyweight是, flyweightfactory提供一個已經創建的實例, 或者創建一個 """ def __init__(self): self.__flyweights = dict() fx = ConcreteFlyweight() self.__flyweights["X"] = fx fy = ConcreteFlyweight() self.__flyweights["Y"] = fy def add_flyweight(self, key, flyweight): self.__flyweights[key] = flyweight def get_flyweight(self, key): flyweight = self.__flyweights.get(key) if not flyweight: flyweight = ConcreteFlyweight() self.__flyweights[key] = flyweight return flyweightif __name__ == '__main__': f = FlyweightFactory() flyweight = f.get_flyweight("X") flyweight.operation(100)proxy.py#!/usr/bin/env python# encoding: utf-8"""代理模式為其他對象提供一種代理以控制這個對象的訪問遠程代理/虛擬代理/安全代理/智能指引"""from abc import ABCMeta, abstractmethodclass Subject(object): """ 定義了RealSubject和Proxy的共用接口 這樣就在任何使用realsubject的地方都可以使用proxy """ __metaclass__ = ABCMeta @abstractmethod def request(self): passclass RealSubject(Subject): """ 定義了真正的實體 """ def request(self): print "hello"class Proxy(Subject): """ 保存一個引用使得代理可以訪問尸體并提供一個與subject的接口相同的接口, 這樣代理就可以用來替代實體 """ def __init__(self): self.__realsubject = RealSubject() def request(self): self.__realsubject.request()if __name__ == '__main__': proxy = Proxy() proxy.request()
新聞熱點
疑難解答