原型模式: 用于创建重复的对象,同时保证性能 这种模式首先是实现了一个「原型接口」, 该接口用于创建当前对象的克隆, 例如一个对象需要在一个高代价的数据库操作之后被创建,我们可以缓存该对象,在下一个请求时返回它的克隆,需要时再更新数据库,以此来减少数据库调用 使用场景: 1、资源优化场景 2、类初始化需要消耗非常多资源 3、一个对象多个修改者的场景

    1. import copy
    2. from collections import OrderedDict
    3. class Book(object):
    4. def __init__(self, name, authors, price, **kwargs):
    5. self.name = name
    6. self.authors = authors
    7. self.price = price
    8. # 添加额外属性
    9. self.__dict__.update(kwargs)
    10. print("完成实例化了")
    11. def __str__(self):
    12. mylist = []
    13. ordered = OrderedDict(sorted(self.__dict__.items()))
    14. for key in ordered.keys():
    15. mylist.append('{}: {}'.format(key, ordered[key]))
    16. if key == "price":
    17. mylist.append("$")
    18. mylist.append('\n')
    19. return ''.join(mylist)
    20. class ProtoType(object):
    21. """原型接口"""
    22. def __init__(self):
    23. """初始化一个原型列表"""
    24. self.objs = dict()
    25. def register(self, identifier, obj):
    26. """在原型列表中注册原型对象"""
    27. self.objs[identifier] = obj
    28. def unregister(self, identifier):
    29. """从原型列表中删除原型对象"""
    30. del self.objs[identifier]
    31. def clone(self, identifier, **kwargs):
    32. """根据identifier 在原型列表中查找原型对象并克隆"""
    33. found = self.objs.get(identifier)
    34. if not found:
    35. raise ValueError('Incorrect object identifier: %s' % identifier)
    36. obj = copy.deepcopy(found)
    37. # 用新的属性值替换原型对象中的对应属性
    38. obj.__dict__.update(kwargs)
    39. return obj
    40. if __name__ == '__main__':
    41. b1 = Book('python', ('zaygee', 'hoan'), price=10, puhlisher="popping J")
    42. print(b1)
    43. prototype = ProtoType()
    44. ids = "1111"
    45. prototype.register(ids, b1)
    46. b2 = prototype.clone(ids, name="java", price=11, puhlisher="zaygee")
    47. print(b2)
    48. print("id(b1) == id(b2): ", id(b1) == id(b2))
    49. """
    50. 完成实例化了
    51. authors: ('zaygee', 'hoan')
    52. name: python
    53. price: 10$
    54. puhlisher: popping J
    55. authors: ('zaygee', 'hoan')
    56. name: java
    57. price: 11$
    58. puhlisher: zaygee
    59. id(b1) == id(b2): False
    60. """