Prototype is relative to replication 、 Cloning , But different from the template , The template creates exactly the same thing , The prototype creates something that allows differentiation and personalization .
The realization idea of prototype pattern is :“ Deep copy ” and “ Property update ”. Define a prototype , Design a copy interface , There is no need to instantiate classes frequently , Just copy .
advantage :
To realize self introduction of multiple people , The general method is that everyone creates an object , But after using the prototype pattern , Just instantiate an object ( Standard person ), The latter people have used this standard to realize personalization .
import copy
class Information:
""" Personal information """
def __init__(self):
self.name = None
self.ager = None
self.height = None
def run(self):
""" How to introduce yourself :return: """
print(" My name is {}: Age :{} height :{}".format(self.name, self.ager, self.height))
class Prototype:
def __init__(self, obj):
self.copy_object = obj()
def clone(self, **attr):
obj = copy.deepcopy(self.copy_object)
obj.__dict__.update(attr)
return obj
if __name__ == '__main__':
test = Prototype(Information)
a = test.clone(name=' Zhang Shan ', ager="30", height='170cm')
a.run()
b = test.clone(name=' Li Fei ', ager="20", height='190cm')
b.run()