[关闭]
@spiritnotes 2016-06-08T15:46:22.000000Z 字数 734 阅读 1573

《Python编程实战:运用设计模式、并发和程序库创建高质量程序》

Python 读书笔记 DOING


1 Python的创建型设计模式

1.1 抽象工厂模式

经典模式的抽象工厂:多个factory,含有相同的方法,在实际使用通过传入不同的factory来达到创建不同的对象

可以通过**locals()产生关键子参数用于简化函数调用

  1. def __init__(self, x):
  2. x += 8
  3. y += 4
  4. self.c = C.format(**locals()) # format_map(locals())

Python风格的抽象工厂模式:

  1. class DiagramFactory:
  2. @classmethod # 没有状态,直接使用类方法
  3. def make_diagram(cls, width, height):
  4. return cls.Diagram(width, height) # 代码公用了,新类只要定义Diagram属性即可
  5. class TxtDiagram:
  6. def __init__(self, width, height):
  7. pass
  8. class TextDiagramFactory(DiagramFactory):
  9. Diagram = TxtDiagram # 或者直接在该类里面定义

1.2 建造者模式

适用于需要把复杂对象各部分的细节与其创建流程相分离的场合

  1. def create_somthing(builder):
  2. builder.add_a(...) # 给予创建细节的参数
  3. builder.add_b(...)
  4. return builder.form()
  5. class AbcBuilder(metaclass=abc.ABCMeta): # 抽象类有运行期开销
  6. @abc.abstractmethod
  7. def add_a(self, ...):
  8. ...

1.3 工厂方法模式

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注