人的理想志向往往和他的能力成正比
"""原型模式"""
import copy
class Prototype:
value = 'default'
def clone(self, **attrs):
"""克隆一个原型,并更新内部属性字典"""
obj = copy.deepcopy(self)
obj.__dict__.update(attrs)
return obj
class PrototypeDispatcher:
def __init__(self):
self._objects = {}
def get_objects(self):
"""获取所有对象"""
return self._objects
def register_object(self, name, obj):
"""注册一个对象"""
self._objects[name] = obj
def unregister_object(self, name):
"""注销一个对象"""
del self._objects[name]
def main():
dispatcher = PrototypeDispatcher()
prototype = Prototype()
a = prototype.clone(value='a-value', category='a')
b = prototype.clone(value='b-value', is_checked=True)
d = prototype.clone()
dispatcher.register_object('objecta', a)
dispatcher.register_object('objectb', b)
dispatcher.register_object('default', d)
"""
Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。
"""
print([{n: p.value} for n, p in dispatcher.get_objects().items()])
if __name__ == '__main__':
main()
运行结果如图: