设计模式八(原型模式,python语言实现)

基本原理请参考相关书籍。

直接给实例

 

说明:原型就是克隆的对象。比如在企业的刀具生产中,要生产一种铣刀mill,数量10000,设计过程很复杂,设计完后经过试加工合格,后继工作不会对每把铣刀都重新设计,而是用这一个设计通过加工克隆出合格的产品。生产完后每把铣刀(克隆体)需要在标签上有差异(打标)

 


 

#python 语言很容易通过deepcopy实现深度复制。

 

# -*- coding: utf-8 -*-

#######################################################
# 
# Prototype.py
# Python implementation of the Class Prototype
# Generated by Enterprise Architect
# Created on:      11-十二�2012 8:21:43
# 
#######################################################

 


from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future_builtins import *
    
   
import sys
from PySide.QtCore import *
from PySide.QtGui import  *
from copy import *

 


class Prototype(object):
    """This class declares an interface for cloning itself.
    """

    def __init__(self, label='blank:'):
 super(Prototype,self).__init__()
 self.label=label
 pass

    def Clone(self):
        pass

 

 

 

class Drill(Prototype):
    """This class implements an operation for cloning itself.
    """
    def __init__(self,label='dill:'):
 super(Drill,self).__init__(label)
        pass
    
    def AppendLabel(self,label):
 self.label+=label
 
    #----------------------------------------------------------------------
    def ShowLabel(self):
 """"""
 print(self.label)
 pass
 
    def Clone(self):
        return deepcopy(self)
        pass

class Mill(Prototype):
    """This class implements an operation for cloning itself.
    """
    """This class implements an operation for cloning itself.
    """
    def __init__(self,label='mill:'):
 super(Mill,self).__init__(label)
        pass
    
    def AppendLabel(self,label):
 self.label+=label
 
    #----------------------------------------------------------------------
    def ShowLabel(self):
 """"""
 print(self.label)
 pass
 
    def Clone(self):
        return deepcopy(self)
        pass
 
 
 
#客户端:
 
    
if(__name__=="__main__"):
    
    class Client(object):
 """This class creates a new object by asking a prototype to clone itself.
 """
 m_Prototype= Prototype()
    
    
 def Clone(self,prototype):
     return  prototype.Clone()
     pass
    
 def __init__(self, parent = None):
     pass
 pass
    
    
    
    client=Client()
    mill_prototype=Mill()
    mill_prototype.AppendLabel('label ');
    
    mill_one=client.Clone(mill_prototype)
    mill_one.AppendLabel('one')
    
    mill_two=client.Clone(mill_prototype)
    mill_two.AppendLabel('two')
    
    mill_prototype.ShowLabel()
    mill_one.ShowLabel()
    mill_two.ShowLabel()


   

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值