原型模式,也是用于創建對象時的一種設計方法。
主要應用場景是:每次初始化某個對象時,需要傳遞大量的參數,很不方便,此時,可以使用原型模式,在已經創建并初始化的對象基礎上,可以快速而又方便創建新的不同對象。
主要原理:使用深拷貝,復制一個已創建的對象,然后使用__dict__.update()方法更新已創建對象中的參數值方式創建新對象。
背景知識:在python中的類中,__dict__是一個字典,保存了所有該類中的變量,函數等參數。
?
#coding=utf-8
import copy
from collections import OrderedDict
class book(object):
def __init__(self,name,authors,price,**rest):
self.name = name
self.authors = authors
self.price = price
self.__dict__.update(rest)
def __str__(self):
mylist=[]
ordered=OrderedDict(sorted(self.__dict__.items()))
for i in ordered.keys():
mylist.append('{}:{}'.format(i,ordered[i]))
if i=='price':
mylist.append('$')
mylist.append('\n')
return ''.join(mylist)
class prototype():
def __init__(self):
self.objects=dict()
def register(self,identifier,obj):
self.objects[identifier]=obj
def unregister(self,identifier):
del self.objects[identifier]
def clone(self,identifier,**attr):
found=self.objects.get(identifier)
if not found:
raise ValueError('Incorrect object identifier:{}'.format(identifier))
obj=copy.deepcopy(found)
obj.__dict__.update(attr) #這里不能寫成obj.update(attr),深度拷貝的對象中沒有這個update()函數
return obj
if __name__ == "__main__":
b1 = book('The C Programming Language', ('Brian W. Kernighan', 'Dennis M.Ritchie'),
price=118, publisher='Prentice Hall', length=228, publication_date='1978-02-22',
tags=('C', 'programming', 'algorithms', 'data structures'))
prototype = prototype()
cid = 'k&r-first'
prototype.register(cid, b1)
b2 = prototype.clone(cid, name='The C Programming Language(ANSI)', price=48.99,
length=274, publication_date='1988-04-01', edition=2)
for i in (b1, b2):
print(i)
print("ID b1 : {} != ID b2 : {}".format(id(b1), id(b2)))
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
