鍍金池/ 教程/ Python/ 原型設(shè)計(jì)模式
反模式
隊(duì)列
適配器設(shè)計(jì)模式
享元設(shè)計(jì)模式
Python設(shè)計(jì)模式
工廠(chǎng)模式
模板設(shè)計(jì)模式
構(gòu)建器(Builder)設(shè)計(jì)模式
Python設(shè)計(jì)模式概要
命令設(shè)計(jì)模式
Python設(shè)計(jì)模式簡(jiǎn)介
觀察者設(shè)計(jì)模式
代理設(shè)計(jì)模式
異常處理
責(zé)任鏈設(shè)計(jì)模式
字典實(shí)現(xiàn)
抽象工廠(chǎng)設(shè)計(jì)模式
Python并發(fā)(多線(xiàn)程)
策略設(shè)計(jì)模式
門(mén)面(Facade)設(shè)計(jì)模式
原型設(shè)計(jì)模式
迭代器設(shè)計(jì)模式
集合
單例模式
列表數(shù)據(jù)結(jié)構(gòu)
狀態(tài)設(shè)計(jì)模式
模型視圖控制器(MVC)模式
裝飾器設(shè)計(jì)模式
面向?qū)ο蟾拍畹膶?shí)現(xiàn)
面向?qū)ο笤O(shè)計(jì)模式
字符串和序列化

原型設(shè)計(jì)模式

原型設(shè)計(jì)模式有助于隱藏該類(lèi)創(chuàng)建實(shí)例的復(fù)雜性,在對(duì)象的概念將與從頭創(chuàng)建的新對(duì)象的概念不同。

如果需要,新復(fù)制的對(duì)象可能會(huì)在屬性中進(jìn)行一些更改。這種方法節(jié)省了開(kāi)發(fā)產(chǎn)品的時(shí)間和資源。

如何實(shí)現(xiàn)原型模式?

現(xiàn)在讓我們看看如何實(shí)現(xiàn)原型模式。代碼實(shí)現(xiàn)如下 -

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

執(zhí)行上面程序,將生成以下輸出 -

輸出中,使用現(xiàn)有的對(duì)象創(chuàng)建新對(duì)象,并且在上述輸出中清晰可見(jiàn)。