原始基元模式-设计模式

'''
ROTOTYPE——原始模型模式?
  跟MM用QQ聊天,一定要说些深情的话语了,我搜集了好多肉麻的情话,需要时只要copy出来放到QQ里面就行了,这就是我的情话prototype了。(100块钱一份,你要不要)   原始模型模式:通过给出一个原型对象来指明所要创建的对象的类型,然后用复制这个原型对象的方法创建出更多同类型的对象。
  原始模型模式允许动态的增加或减少产品类,产品类不需要非得有任何事先确定的等级结构,原始模型模式适用于任何的等级结构。缺点是每一个类都必须配备一个克隆方法。


容:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。


使用场景:


通过动态装载;
为了避免创建一个与产品类层次平行的工厂类层次时;
当一个类的实例只能有几个不同状态组合中的一种时。
建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。


'''
# import copy
#
# class Prototype(object):
#     def __init__(self):
#         self._objects={}
#
#     def register_object(self,name,obj):
#         '''Register an object '''
#         self._objects[name]=obj
#     def unregister_object(self,name):
#         '''unregister an object'''
#         del self._objects[name]
#     def clone(self,name,**attr):
#         '''Clone a registered object and update inner attributes dictionary'''
#         obj=copy.deepcopy(self._objects.get(name))
#         obj.__dict__.update(attr)
#         return obj
#
#
# def main():
#     class A(object):
#         def __str__(self):
#             return "I am A"
#
#     a=A()
#     prototype=Prototype()
#     prototype.register_object("a",a)
#     b=prototype.clone("a",a=1,b=2,c=3)
#     print(a)
#     print(b.a,b.b,b.c)
#
# if __name__ =="__main__":
#     main()


#=================2===================
import copy


class Prototype(object):
    def __init__(self):
        self._objects={}


    def rigister_object(self,name,obj):
        self._objects[name] = obj


    def unrigister_object(self,name):
        del self._objects[name]


    def clone(self,name,**attr):
        obj=copy.deepcopy(self._objects.get(name))
        obj.__dict__.update(attr)
        return obj






def main():
    class stu(object):
        print("I am is haoren ")
    a=stu()
    p=Prototype()
    p.rigister_object("a",a)
    b=p.clone("a",b=1,c=3,d=5)
    print(a)
    print(b.b,b.c)
if __name__ =="__main__":
    main()

猜你喜欢

转载自blog.csdn.net/weixin_42040854/article/details/80613054