程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python design pattern - creation pattern - prototype pattern

編輯:Python

Catalog

List of articles

  • Catalog
  • Archetypal model
  • Application scenarios
  • Code example

Archetypal model

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 :

  • Reduce the loss caused by object instantiation , And implement dynamic loading .

Application scenarios

Code example

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()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved