用原型實例指定要建立的對象的類型,經過拷貝這些原型建立新的對象python
import copy class Prototype: def __init__(self): self._objects = {} @property def register_object(self): return self._objects def register_object(self, name, obj): self._objects[name] = obj def unregister_object(self, name): del self._objects[name] def clone(self, name, **attr): obj = copy.deepcopy(self._objects[name]) obj.__dict__.update(attr) return obj def main(): class A: pass a = A() prototype = Prototype() prototype.register_object('a', a) b = prototype.clone('a', a = 1, b = 2, c = 3) print(a) print(b) print(b.a, b.b, b.c) if __name__=="__main__": main()
這裏使用的是深拷貝,能夠看到運行結果prototype
<__main__.A object at 0x00FF3350> <__main__.A object at 0x00FFA490> 1 2 3
這裏a, b都是A的實例,可是卻不在同一個地址上,在原型創模式建立指定的對象的時候,若是是淺拷貝,只能拷貝對象中的基本數據類型,因此這裏使用的是深拷貝的方式code