设计模式(python实现)--原型模式(Prototype)

2020-02-02  本文已影响0人  远行_2a22

Prototype

动机(motivation)

模式定义

使用原型实例指定创建对象的种类,然后通过拷贝这些原型来创建新的对象。
——《设计模式》GoF

要点总结

例子

# -*- coding: utf-8 -*-
import copy
from collections import OrderedDict


class Book(object):
    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(object):
    def __init__(self):
        self.objects = dict()

    def register(self, identifier, obj):
        self.objects[identifier] = obj

    def unregister(self, identifier):
        if identifier in self.objects:
            del self.objects[identifier]

    def clone(self, identifier, **kwargs):
        prototype_obj = self.objects.get(identifier)
        if not prototype_obj:
            raise ValueError('Incorrect object identifier: {}'.format(identifier))
        obj = copy.deepcopy(prototype_obj)
        obj.__dict__.update(kwargs)
        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()
上一篇 下一篇

猜你喜欢

热点阅读