原型模式,也是用于創(chuàng)建對(duì)象時(shí)的一種設(shè)計(jì)方法。
主要應(yīng)用場(chǎng)景是:每次初始化某個(gè)對(duì)象時(shí),需要傳遞大量的參數(shù),很不方便,此時(shí),可以使用原型模式,在已經(jīng)創(chuàng)建并初始化的對(duì)象基礎(chǔ)上,可以快速而又方便創(chuàng)建新的不同對(duì)象。
主要原理:使用深拷貝,復(fù)制一個(gè)已創(chuàng)建的對(duì)象,然后使用__dict__.update()方法更新已創(chuàng)建對(duì)象中的參數(shù)值方式創(chuàng)建新對(duì)象。
背景知識(shí):在python中的類中,__dict__是一個(gè)字典,保存了所有該類中的變量,函數(shù)等參數(shù)。
?
#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),深度拷貝的對(duì)象中沒(méi)有這個(gè)update()函數(shù)
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)))
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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