zoukankan      html  css  js  c++  java
  • 原型模式

    一、内容

    用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
    原型模式本质就是克隆对象,所以在对象初始化操作比较复杂的情况下,很实用,能大大降低耗时,提高性能,因为“不用重新初始化对象,而是动态地获得对象运行时的状态”。

    浅拷贝(Shallow Copy):指对象的字段被拷贝,而字段引用的对象不会被拷贝,拷贝的对象和源对象只是名称相同,但是他们共用一个实体。
    深拷贝(deep copy):对对象实例中字段引用的对象也进行拷贝。

    二、代码实例

    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('
    ')
                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()
    
    """
    >>> python3 prototype.py
    authors: ('Brian W. Kernighan', 'Dennis M. Ritchie')
    length: 228
    name: The C Programming Language
    price: 118$
    publication_date: 1978-02-22
    publisher: Prentice Hall
    tags: ('C', 'programming', 'algorithms', 'data structures')
    
    
    authors: ('Brian W. Kernighan', 'Dennis M. Ritchie')
    edition: 2
    length: 274
    name: The C Programming Language (ANSI)
    price: 48.99$
    publication_date: 1988-04-01
    publisher: Prentice Hall
    tags: ('C', 'programming', 'algorithms', 'data structures')
    
    ID b1 : 140004970829304 != ID b2 : 140004970829472
    """
  • 相关阅读:
    Access denied for user 'root'@'localhost' (using password:YES) 解决方案
    MyBatis报错 Parameter '0' not found. Available parameters are [arg1, arg0, param1, param2]
    MySQL类型float double decimal的区别
    数据库--MyBatis的(insert,update,delete)三种批量操作
    mybatis的模糊查询格式
    java 24小时倒计时案例
    Project facet Java version 1.7 is not supported.解决方法
    eclipse中将项目加载到tocat报错:Tomcat version 6.0 only supports J2EE 1.2, 1.3, 1.4, and Java EE 5 Web modules
    网络爬虫的学习
    关于电脑安装多个版本JDK后使用时的切换
  • 原文地址:https://www.cnblogs.com/zcfx/p/11336042.html
Copyright © 2011-2022 走看看