Factory 方法
應用特性:需要產生的對象經常需要增改時,抽離出易變的內容並獨立放置在一個類中
結構特性:一個工廠類分離成多個子工廠類,分別只做一件事
UML:
#!/usr/bin/env python #encoding: utf-8 class factory_base: def __init__(self): pass def create_method(self): pass class factory1(factory_base): def __init__(self): pass def create_method(self): return class1()class factory2(factory_base): def __init__(self): pass def create_method(self): return class2() class class_base: def __init__(self): pass def do_something(self, something): pass class class1(class_base): def __init__(self): pass def do_something(self, something): print something class class2(class_base): def __init__(self): pass def do_something(self, something): print something + ' WITH ' + something if '__main__' == __name__: factory1_obj = factory1() factory2_obj = factory2() class1_obj = factory1_obj.create_method() class2_obj = factory2_obj.create_method() class1_obj.do_something('something') class2_obj.do_something('something') print factory1_obj.__class__ print factory2_obj.__class__ print class1_obj.__class__ print class2_obj.__class__
結果:
somethingsomething WITH something__main__.factory1__main__.factory2__main__.class1__main__.class2