原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
原型模式本质就是克隆对象,所以在对象初始化操作比较复杂的情况下,很实用,能大大降低耗时,提高性能,因为“不用重新初始化对象,而是动态地获得对象运行时的状态”。
浅拷贝(Shallow Copy):指对象的字段被拷贝,而字段引用的对象不会被拷贝,拷贝的对象和源对象只是名称相同,但是他们共用一个实体。
深拷贝(deep copy):对对象实例中字段引用的对象也进行拷贝。
-
-
-
-
-
- import copy
-
- def printInfo(info):
- print unicode(info, 'utf-8').encode('gbk')
-
-
- class ICloneable:
- def shallowClone(self):
- return copy.copy(self)
-
- def deepClone(self):
- return copy.deepcopy(self)
-
-
- class WorkExperience(ICloneable):
- workData = ""
- company = ""
- pass
-
-
- class Resume(ICloneable):
- name = ""
- sex = '未知'
- age = 0
- work = None
-
- def __init__(self, name, work = WorkExperience()):
- self.name = name
- self.work = work;
-
- def setPersonInfo(self, sex, age):
- self.sex = sex
- self.age = age
-
- def setWorkExperience(self, workData, company):
- self.work.workData = workData
- self.work.company = company
-
- def display(self):
- printInfo('%s, %s, %d' % (self.name,self.sex,self.age))
- printInfo('%s, %s' % (self.work.workData, self.work.company))
-
- def clientUI():
- a = Resume('大鸟')
- a.setPersonInfo('男',29)
- a.setWorkExperience("1998-2000","XX公司")
-
-
- b = a.shallowClone()
- b.setWorkExperience("2000-2006","YY公司")
-
-
- c = a.deepClone()
- c.setWorkExperience("2006-2009","ZZ公司")
-
- b.display()
- a.display()
- c.display()
- return
-
- if __name__ == '__main__':
- clientUI();
类图: