创建型模式---原型模式

原型模式

原型设计模式帮助我们创建对象的克隆,其最简单的形式就是一个clone()函数,接受一个对象作为输入参数,返回输入对象的一个副本。在Python中,这可以使用copy.deepcopy()函数来完成。
现实生活中的例子:有丝分裂,即细胞分裂的过程,是生物克隆的一个例子。在这个过程中,细胞核分裂产生两个新的细胞核,其中每个都有与原来细胞完全相同的染色体和DNA内容。
import copy
from collections import OrderedDict

class Book:
    def __init__(self,name,authors,price,**rest):
        """rest的例子有:出版商、长度、标签、出版日期"""
        self.name = name
        self.authors = authors
        self.price = price
        self.__dict__.update(rest)

    def __str__(self):
        mylist = []
        #因为我们未知所有被添加参数的名称,但又需要访问内部字典将这些参数应用到__str__()中
        #且字典无序,所有利用Ordereddict来强制元素有序,否则,每次打印结果会有所不同。
        ordered = OrderedDict(sorted(self.__dict__.items()))
        for i in ordered.keys():
            mylist.append('{}:{}'.format(i,ordered[i]))
            if i=='price':
                mylist.append('$')
            mylist.append('\n')
        return ''.join(mylist)

#Prototype实现了原型设计模式,其核心是clone()方法
class Prototype:
    def __init__(self):
        self.objects = dict()

    def register(self,identifier,obj):
        self.objects[identifier] = obj

    def unregister(self,identifier):
        del self.objects[identifier]

    def clone(self,identifier,**attr):
        found = self.objects.get(identifier)
        if not found:
            raise ValueError('Incorrect object identifier:{}'.format(identifier))
        obj = copy.deepcopy(found)
        obj.__dict__.update(attr)
        return obj

def main():
    b1 = Book("The C Programming Language",("Brain W. Kerbighan","Dennis M'Rithchie"),price = 118,
              publisher="Prentice Hall",length=228,publication_date="1978-02-22",
              tags=('C','programming','algorithms'))
    prototype = Prototype()
    cid = "k&r-first"
    prototype.register(cid,b1)
    b2 = prototype.clone(cid,name="The C Programming Language(ANSI)",price=48.99,
                         length=274,publication_date='1988-04-01',edition=2)

    for i in (b1,b2):
        print(i)
    print("ID b1:{} != ID b2:{}".format(id(b1),id(b2)))

if __name__ == '__main__':
    main()

小结

原型模式用于创建对象的完全副本。确切的说,创建一个对象的副本可以指代以下两件事情。
    当创建一个浅副本时,副本依赖引用;
    当创建一杯深副本时,副本复制所有东西。
第一种情况中,我们关注提升性能优化和优化内存使用,在对象之间引入数据共享,但需要小心地修改数据,因为所有变更对所有副本都是可见的。
第二种情况中,我们希望能够对一个副本进行更改而不会影响其他对象。

猜你喜欢

转载自www.cnblogs.com/xiaoshayu520ly/p/10981587.html