Python设计模式 专题
您的位置:python > Python设计模式专题 > 原型设计模式
原型设计模式
作者:--    发布时间:2019-11-20

原型设计模式有助于隐藏该类创建实例的复杂性,在对象的概念将与从头创建的新对象的概念不同。

如果需要,新复制的对象可能会在属性中进行一些更改。这种方法节省了开发产品的时间和资源。

如何实现原型模式?

现在让我们看看如何实现原型模式。代码实现如下 -

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):

   """ concrete prototype. """

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

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

class objectfactory:

   """ manages prototypes.
   static factory, that encapsulates prototype
   initialization and then allows instatiation
   of the classes from these prototypes.
   """

   __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 "%s: %s" % (instance.gettype(), instance.getvalue())

   instance = objectfactory.gettype1value2()
   print "%s: %s" % (instance.gettype(), instance.getvalue())

   instance = objectfactory.gettype2value1()
   print "%s: %s" % (instance.gettype(), instance.getvalue())

   instance = objectfactory.gettype2value2()
   print "%s: %s" % (instance.gettype(), instance.getvalue())

if __name__ == "__main__":
   main()

执行上面程序,将生成以下输出 -

输出中,使用现有的对象创建新对象,并且在上述输出中清晰可见。


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册