Python design pattern—prototype pattern

I shared several articles about design patterns in the previous period, and today I continue to share design patterns-prototype patterns

  • We will use prototype instances to specify the types of objects to be created, and create new objects by deep copying these prototypes.

  • The essence of the prototype mode is to clone an object, so it is very practical when the object initialization operation is more complicated, which can greatly reduce time-consuming and improve performance.

  • In the prototype mode, we don't need to reinitialize the object, but dynamically obtain the runtime state of the object.

 

The meaning of deep copy

Shallow Copy: Refers to the object's field being copied, and the object referenced by the field will not be copied. The copied object and the source object have the same name, but they share the same entity.
Shallow copy will copy the content of the object and its references or sub-object references, but will not copy the referenced content and the sub-objects themselves.

 

Deep copy: Copy the object referenced by the field in the object instance. Deep copy not only copies references to objects and content, but also copies the referenced content. Therefore, in general, the deep copy is more complete than the shallow copy, but it also takes up more resources (including time and space resources).

 

scenes to be used

When we have an iterative project to update, and the object instance in the second version needs to be modified on the basis of the first version, we can use the prototype mode to achieve this at this time, which greatly saves time and improves Efficiency.

 

advantage

Prototype mode is used to create complex or time-consuming instances: copy an existing instance to make the program run more efficiently. And for the factory pattern, the prototype pattern reduces the construction of subclasses.

 

Disadvantage

Each product class must be configured with a clone method, and this clone method needs to consider the function of the class as a whole.

 

Python code implementation

import copy
from collections import OrderedDict

#定义一个人的类
class Person():
    def __init__(self,name,age,high,sex,**info):
        self.name=name
        self.age=age
        self.high=high
        self.sex=sex
        #可以为实例添加其他额外属性,但必须是key:value格式的属性
        self.__dict__.update(info)

    #当使用print输出对象的时候,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据
    def __str__(self):
        myinfo=[]
        #OrderedDict 是 collections 提供的一种数据结构, 它提供了有序的dict结构。
        order_dict=OrderedDict(self.__dict__.items())
        for i in order_dict.keys():
            myinfo.append('{}:{}'.format(i,order_dict[i]))
            myinfo.append('\n')
        return ''.join(myinfo)

 

Define a prototype class

class Prototype():
    def __init__(self):
        self.objects=dict() #定义原型对象字典表

    #在原型字典表中注册原型对象
    def register(self,id,obj):
        self.objects[id]=obj

    #在原型字典表中删除原型对象
    def destory(self,id):
        del self.objects[id]

    #根据 id 在原型字典表中查找原型对象并克隆
    def clone(self,id,**atter):
        obj1=self.objects.get(id)
        print(obj1)
        if not obj1:
            raise ValueError('Incorrect object id: {}'.format(id))
        obj2=copy.deepcopy(obj1)
        obj2.__dict__.update(atter)
        return obj2


if __name__ == '__main__':
    tony=Person('tony',34,170,'man',job='tester',birthday='2000-01-01',hobby='catch fish')
    print(tony)

    prototype=Prototype()
    prototype.register(1001,tony)
    tom=prototype.clone(1001,name='tom',age='19',birthday='2010-02-02')

    for i in (tony,tom):
        print(i)
    #输出两个Person对象是否是相同的id值
    print("id tony : {} != id tom : {}".format(id(tony), id(tom)))

 

The output content is as follows

name:tony
age:34
high:170
sex:man
job:tester
birthday:2000-01-01
hobby:catch fish

name:tony
age:34
high:170
sex:man
job:tester
birthday:2000-01-01
hobby:catch fish

name:tony
age:34
high:170
sex:man
job:tester
birthday:2000-01-01
hobby:catch fish

name:tom
age:19
high:170
sex:man
job:tester
birthday:2010-02-02
hobby:catch fish

id tony : 2930225522448 != id tom : 2930225522504

Welcome to pay attention to [The Way of Infinite Testing] public account , reply [Receive Resources]
Python programming learning resources dry goods,
Python+Appium framework APP UI automation,
Python+Selenium framework Web UI automation,
Python+Unittest framework API automation,

Resources and codes are sent for free~
There is a QR code of the official account at the bottom of the article, you can just scan it on WeChat and follow it.

Remarks: My personal public account has been officially opened, dedicated to the sharing of test technology, including: big data testing, functional testing, test development, API interface automation, test operation and maintenance, UI automation testing, etc., WeChat search public account: "Infinite The Way of Testing", or scan the QR code below:

 Add attention and let us grow together!

Guess you like

Origin blog.csdn.net/weixin_41754309/article/details/115303161