继续另一种类型。
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()
新闻热点
疑难解答