@spiritnotes
2016-06-08T15:46:22.000000Z
字数 734
阅读 1724
Python
读书笔记
DOING
经典模式的抽象工厂:多个factory,含有相同的方法,在实际使用通过传入不同的factory来达到创建不同的对象
可以通过**locals()产生关键子参数用于简化函数调用
def __init__(self, x):
x += 8
y += 4
self.c = C.format(**locals()) # format_map(locals())
Python风格的抽象工厂模式:
class DiagramFactory:
@classmethod # 没有状态,直接使用类方法
def make_diagram(cls, width, height):
return cls.Diagram(width, height) # 代码公用了,新类只要定义Diagram属性即可
class TxtDiagram:
def __init__(self, width, height):
pass
class TextDiagramFactory(DiagramFactory):
Diagram = TxtDiagram # 或者直接在该类里面定义
适用于需要把复杂对象各部分的细节与其创建流程相分离的场合
def create_somthing(builder):
builder.add_a(...) # 给予创建细节的参数
builder.add_b(...)
return builder.form()
class AbcBuilder(metaclass=abc.ABCMeta): # 抽象类有运行期开销
@abc.abstractmethod
def add_a(self, ...):
...