100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > python 设计模式 原型模式_python设计模式–原型模式

python 设计模式 原型模式_python设计模式–原型模式

时间:2019-11-23 16:14:52

相关推荐

python 设计模式 原型模式_python设计模式–原型模式

套用书里的一个例子,两年前你写了一本书,现在你要在此书 的基础上修订一版,你会在新版本中加入一些最新的元素,但是与之前的书相比你有很多的地方其实是不用修改的,但是你又不想直接把上一版拿过来改,万一改的不好也回不到之前的版本了,所以你想把之前的第一版复制一份出来,然后在副本上再次开发。

写到这里顿时想到了git版本管理,你在当前的master分支上开启新的分支,不就是相当于copy一份当前的代码,这就是原型模式的思想

copy当前的对象,在副本的基础上继续开发,这二者都不受影响

下面给出一个原型模式的代码

# coding: utf-8

import copy

from collections import OrderedDict

class Book:

def __init__(self, name, authors, price, **rest):

'''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)

return obj

def 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)))

if __name__ == '__main__':

main()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。