PROTOTYPE DESIGN:PYTHON

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/boyun58/article/details/83409968

原型设计模式有助于隐藏该类创建实例的复杂性,在对象的概念将与从头创建的新对象的概念不同。如果需要,新复制的对象可能会在属性中进行一些更改。这种方法节省了开发产品的时间和资源。

import copy


class Prototype:
    _type = None
    _value = None

    def clone(self):
        pass

    def getType(self):
        return self._type

    def getValue(self):
        return self._value


class Type1(Prototype):

    def __init__(self, number):
        self._type = "TYPE1"
        self._value = number

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


class Type2(Prototype):

    def __init__(self, number):
        self._type = "TYPE2"
        self._value = number

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


class ObjectFactory:

    __type1Value1 = None
    __type1Value2 = None
    __type2Value1 = None
    __type2Value2 = None

    @staticmethod
    def initialize():
        ObjectFactory.__type1Value1 = Type1(1)
        ObjectFactory.__type1Value2 = Type1(2)
        ObjectFactory.__type2Value1 = Type2(1)
        ObjectFactory.__type2Value2 = Type2(2)

    @staticmethod
    def getType1Value1():
        return ObjectFactory.__type1Value1.clone()

    @staticmethod
    def getType1Value2():
        return ObjectFactory.__type1Value2.clone()

    @staticmethod
    def getType2Value1():
        return ObjectFactory.__type2Value1.clone()

    @staticmethod
    def getType2Value2():
        return ObjectFactory.__type2Value2.clone()


def main():
    ObjectFactory.initialize()

    instance = ObjectFactory.getType1Value1()
    print("{0}: {1}".format(instance.getType(), instance.getValue()))

    instance = ObjectFactory.getType1Value2()
    print("{0}: {1}".format(instance.getType(), instance.getValue()))

    instance = ObjectFactory.getType2Value1()
    print("{0}: {1}".format(instance.getType(), instance.getValue()))

    instance = ObjectFactory.getType2Value2()
    print("{0}: {1}".format(instance.getType(), instance.getValue()))


if __name__ == "__main__":
    main()

猜你喜欢

转载自blog.csdn.net/boyun58/article/details/83409968