python版本的原型模式

一般在初始化信息不发生变化的情况下,克隆是最好的办法。原型模式还应用于知道某些部分会变更但又希望保持原有对象不变时的副本拷贝--引用和副本的问题

# -*- coding:UTF-8 -*-
import abc
from copy import deepcopy


class Prototype(metaclass=abc.ABCMeta):
    def __init__(self, id_):
        self.__id = id_

    @property
    def id(self):
        return self.__id

    @abc.abstractmethod
    def clone(self):
        pass


class ConcretePrototype1(Prototype):
    def clone(self):
        return deepcopy(self)


class ConcretePrototype2(Prototype):
    def clone(self):
        return deepcopy(self)


if __name__ == "__main__":
    p1 = ConcretePrototype1("I")
    c1 = p1.clone()
    print("Cloned:{0}".format(c1.id))

 

posted @ 2018-01-25 16:22  gjw  阅读(97)  评论(0)    收藏  举报