美文网首页
设计模式(python实现)--原型模式(Prototype)

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

作者: 远行_2a22 | 来源:发表于2020-02-02 17:05 被阅读0次

Prototype

动机(motivation)

  • 在软件系统中,经常面临这“某些结构复杂的对象”的创建工作;由于需求的变化,这些对象经常面临着剧烈的变化,但是它们却拥有比较稳定一致的接口。
  • 如何应对这种变化?如何向“客户程序(使用这些对象的程序)”隔离出“这些易变对象”,从而使得依赖这些”易变对象“的客户程序不随着需求改变而改变。

模式定义

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

要点总结

  • Prototype模式同样用于隔离对象的使用者和具体类型(易变类)之间的耦合关系,它同样要求这些“易变类”拥有稳定的接口。
  • Prototype模式对于“如何创建易变类的实体对象“采用”原型克隆“的方法来做,
    它使得我们可以非常灵活地动态创建”拥有某些稳定接口“的新对象——所需工作仅仅是注册一个新类的对象(即原型),
    然后在任何需要的地方Clone。
  • Prototype模式中的Clone方法可以利用某些框架中的序列化来实现深拷贝。

例子

# -*- 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()
  • 例子中以之前创建的Book类对象 b1为原型,创建了对象 b2

相关文章

网友评论

      本文标题:设计模式(python实现)--原型模式(Prototype)

      本文链接:https://www.haomeiwen.com/subject/djpqxhtx.html