原型模式(python)

"""
原型模式:创建原型,可以通过原型拷贝来创建新的对象
python 浅拷贝:copy.copy() 只拷贝当前对象,不拷贝子对象
python 深拷贝:copy.deepcopy() 拷贝当前对象和所有子孙对象
"""
import copy


class Worker(object):
    def __init__(self, a):
        self.a = a

    def set_a(self, a):
        self.a = a

    def display(self):
        print(self.a)


class Prototype(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def set_a(self, a):
        self.a = a

    def show(self):
        print(self.a)
        self.b.display()

    def clone(self):
        return copy.deepcopy(self)


if __name__ == '__main__':
    worker = Worker("aa")
    pro = Prototype("a", worker)
    pro.show()
    print("")
    pro1 = pro.clone()
    pro1.set_a("b")
    worker.set_a("bb")
    pro1.show()
    print("")
    pro.show()

你可能感兴趣的:(设计模式)