Python設(shè)計模式之原型模式實例詳解
本文實例講述了Python設(shè)計模式之原型模式。分享給大家供大家參考,具體如下:
原型模式(Prototype Pattern):用原型實例指定創(chuàng)建對象的種類,并且通過拷貝這些原型創(chuàng)建新的對象
一個原型模式的簡單demo:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
"""
大話設(shè)計模式
設(shè)計模式——原型模式
原型模式(Prototype Pattern):用原型實例指定創(chuàng)建對象的種類,并且通過拷貝這些原型創(chuàng)建新的對象
原型模式是用場景:需要大量的基于某個基礎(chǔ)原型進(jìn)行微量修改而得到新原型時使用
"""
from copy import copy, deepcopy
# 原型抽象類
class Prototype(object):
def clone(self):
pass
def deep_clone(self):
pass
# 工作經(jīng)歷類
class WorkExperience(object):
def __init__(self):
self.timearea = ''
self.company = ''
def set_workexperience(self,timearea, company):
self.timearea = timearea
self.company = company
# 簡歷類
class Resume(Prototype):
def __init__(self,name):
self.name = name
self.workexperience = WorkExperience()
def set_personinfo(self,sex,age):
self.sex = sex
self.age = age
pass
def set_workexperience(self,timearea, company):
self.workexperience.set_workexperience(timearea, company)
def display(self):
print self.name
print self.sex, self.age
print '工作經(jīng)歷',self.workexperience.timearea, self.workexperience.company
def clone(self):
return copy(self)
def deep_clone(self):
return deepcopy(self)
if __name__ == '__main__':
obj1 = Resume('andy')
obj2 = obj1.clone() # 淺拷貝對象
obj3 = obj1.deep_clone() # 深拷貝對象
obj1.set_personinfo('男',28)
obj1.set_workexperience('2010-2015','AA')
obj2.set_personinfo('男',27)
obj2.set_workexperience('2011-2017','AA') # 修改淺拷貝的對象工作經(jīng)歷
obj3.set_personinfo('男',29)
obj3.set_workexperience('2016-2017','AA') # 修改深拷貝的對象的工作經(jīng)歷
obj1.display()
obj2.display()
obj3.display()
運行結(jié)果:
andy
男 28
工作經(jīng)歷 2011-2017 AA
andy
男 27
工作經(jīng)歷 2011-2017 AA
andy
男 29
工作經(jīng)歷 2016-2017 AA
上面類的設(shè)計如下圖:

簡歷類Resume繼承抽象原型的clone和deepclone方法,實現(xiàn)對簡歷類的復(fù)制,并且簡歷類引用工作經(jīng)歷類,可以在復(fù)制簡歷類的同時修改局部屬性
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
基于python實現(xiàn)圖片轉(zhuǎn)字符畫代碼實例
這篇文章主要介紹了基于python實現(xiàn)圖片轉(zhuǎn)字符畫代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09
PyCharm Terminal終端命令行Shell設(shè)置方式
這篇文章主要介紹了PyCharm Terminal終端命令行Shell設(shè)置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01
Python訪問PostgreSQL數(shù)據(jù)庫詳細(xì)操作
postgresql是常用的關(guān)系型數(shù)據(jù)庫,并且postgresql目前還保持著全部開源的狀態(tài),這篇文章主要給大家介紹了關(guān)于Python訪問PostgreSQL數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下2023-11-11

