Prototype pattern (Python recipe)

原文鏈接:http://code.activestate.com/recipes/86651-prototype-pattern/

http://dongweiming.github.io/python-pototype.html

from copy import deepcopy

class Prototype:
    def __init__(self):
        self._objs = {}
        
    def registerObject(self, name, obj):
        """
        register an object.
        """
        self._objs[name] = obj
        
    def unregisterObject(self, name):
        """unregister an object"""
        del self._objs[name]
        
    def clone(self, name, **attr):
        """clone a registered object and add/replace attr"""
        obj = deepcopy(self._objs[name])
        obj.__dict__.update(attr)
        return obj
    

if __name__ == '__main__':
    class A:
        pass


    a=A()
    prototype=Prototype()
    prototype.registerObject("a",a)
    b=prototype.clone("a",a=1,b=2,c=3)


    # 這裏會返回對象a
    print(a)
    # 這裏的對象其實已經被修改成(1, 2, 3)
    print(b.a, b.b, b.c)


發佈了144 篇原創文章 · 獲贊 40 · 訪問量 102萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章