原型模式
模式说明
所谓原型模式就是用原型实例指定创建对象的种类,并且通过复制这些原型创建新的对象。
说到复制,就会有深/浅两种复制,这是面向对象的值类型和引用类型的差异,具体不作说明
模式结构图
程序示例
说明:无
代码:
1 import copy 2 class WorkExp: 3 place="" 4 year=0 5 def __init__(self,p,y): 6 self.place=p 7 self.year=y 8 9 class Resume(WorkExp): 10 name = '' 11 age = 0 12 def __init__(self,n): 13 self.name = n 14 def SetAge(self,a): 15 self.age = a 16 def SetWorkExp(self,exp): 17 self.place = exp.place 18 self.year = exp.year 19 def Display(self): 20 print 'at %s, %s was %s years old,he studied in %s' %(self.year, self.name, self.age,self.place) 21 22 def Clone(self): 23 return self 24 25 if __name__ == "__main__": 26 a = Resume("wang") 27 b = a.Clone() 28 c = copy.copy(a) 29 d = copy.deepcopy(a) 30 a.SetAge(7) 31 b.SetAge(13) 32 c.SetAge(16) 33 d.SetAge(19) 34 35 exp_a = WorkExp('primaryschool',1994) 36 exp_b = WorkExp('middleschool',2000) 37 exp_c = WorkExp('highschool',2003) 38 exp_d = WorkExp('university',2006) 39 40 a.SetWorkExp(exp_a) 41 b.SetWorkExp(exp_b) 42 c.SetWorkExp(exp_c) 43 d.SetWorkExp(exp_d) 44 a.Display() 45 b.Display() 46 c.Display() 47 d.Display()
运行结果:
参考来源:
http://www.cnblogs.com/chenssy/p/3679190.html
http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html
http://www.cnblogs.com/Terrylee/archive/2006/07/17/334911.html