大话设计模式Python实现-原型模式

原型模式(Prototype Pattern):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象

一个原型模式的简单demo:

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 __author__ = 'Andy'
 5 
 6 """
 7 大话设计模式
 8 设计模式——原型模式
 9 原型模式(Prototype Pattern):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象
10 原型模式是用场景:需要大量的基于某个基础原型进行微量修改而得到新原型时使用
11 """
12 from copy import copy, deepcopy
13 
14 # 原型抽象类
15 class Prototype(object):
16 
17     def clone(self):
18         pass
19 
20     def deep_clone(self):
21         pass
22 
23 # 工作经历类
24 class WorkExperience(object):
25 
26     def __init__(self):
27         self.timearea = ''
28         self.company = ''
29 
30     def set_workexperience(self,timearea, company):
31         self.timearea = timearea
32         self.company = company
33 
34 
35 # 简历类   
36 class Resume(Prototype):
37 
38     def __init__(self,name):
39         self.name = name
40         self.workexperience = WorkExperience()
41 
42     def set_personinfo(self,sex,age):
43         self.sex = sex
44         self.age = age
45         pass
46 
47     def set_workexperience(self,timearea, company):
48         self.workexperience.set_workexperience(timearea, company)
49 
50     def display(self):
51         print self.name
52         print self.sex, self.age
53         print '工作经历',self.workexperience.timearea, self.workexperience.company
54 
55     def clone(self):
56         return copy(self)
57 
58     def deep_clone(self):
59         return deepcopy(self)
60 
61 
62 if __name__ == '__main__':
63     obj1 = Resume('andy')
64     obj2 = obj1.clone()  # 浅拷贝对象
65     obj3 = obj1.deep_clone()  # 深拷贝对象
66 
67     obj1.set_personinfo('',28)
68     obj1.set_workexperience('2010-2015','AA')
69     obj2.set_personinfo('',27)
70     obj2.set_workexperience('2011-2017','AA')  # 修改浅拷贝的对象工作经历
71     obj3.set_personinfo('',29)
72     obj3.set_workexperience('2016-2017','AA')  # 修改深拷贝的对象的工作经历
73 
74 
75     obj1.display()
76     obj2.display()
77     obj3.display()

上面类的设计如下图:

简历类Resume继承抽象原型的clone和deepclone方法,实现对简历类的复制,并且简历类引用工作经历类,可以在复制简历类的同时修改局部属性

 

 


作者:Andy
出处:http://www.cnblogs.com/onepiece-andy/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

posted @ 2017-11-06 11:32  Andy冉明  阅读(1017)  评论(0编辑  收藏  举报