The most basic (simple) implementation of the understandable design pattern Flyweight pattern python3

When considering the reasonable use of system memory, the Flyweight mode can reduce performance pressure and reduce resource occupation; the main realization is to realize the reasonable allocation of resources through the idea of ​​sharing data.

When developing a project, in many cases, there will be too many similar objects. The objects have the same common points. The common points can be classified as shared data during programming. The differences can be transferred and assigned in other ways.

For example, if a bottle is made, the appearance of the plate is the same, only the internal data is different. At this time, assuming that a different object is created in a conventional way, the resource allocation of the object is unreasonable.

Assuming that the product has mineral water, only the outer packaging color is different, then Flyweight mode can be used.
The implementation is as follows, first create a new mineral water class:

class BottledWater(object):
    objpool = dict()#记录生成对象
    
    def show(self, color):#显示一下颜色
        print(self.name,'颜色',color)

    def __new__(cls, type):# 使用new 初始化在实例化之前
        obj_ = cls.objpool.get(type, None)#没有找到对象就实例化
        if obj_ == None:
            obj_ = object.__new__(cls)
            cls.objpool[type] = obj_
            obj_.name = type
        return obj_

objpool = dict(): In the mineral water class, an objpool is defined as a pool of record objects (dictionary)
def show(self, color): output the current object name and variable attribute color
def __new__(cls, type): use the new method to create the object before instantiation
obj_ = cls.objpool.get(type, None): find the current type of object in the object pool, If it is not found, it will be None
if obj_ == None:: if the object is not found, the object will be initialized, and the current type of object will be stored in the record pool
obj_.name = type: type is assigned to the current name attribute for subsequent output and display.
Finally, the object obj_ is returned.

After writing the above classes, instantiate the object and check how many objects are stored in the pool:

t1 = BottledWater("矿泉水")
t1.show('红色')
t2 = BottledWater("矿泉水")
t2.show('蓝色')
t3 = BottledWater("矿泉水")
t3.show('绿色')
print('\n')
t1_ = BottledWater("冰红茶")
t1_.show('红色')
t2_ = BottledWater("冰红茶")
t2_.show('蓝色')
t3_ = BottledWater("冰红茶")
t3_.show('绿色')

print('对象一共有:',len(BottledWater.objpool))

Before the flyweight mode is used, the above method of creating new objects should create 6 new objects, but the output shows two:
Insert picture description here
because the type is mineral water and the other is ice tea, there are two types in between; mineral springs After creating a new object, water is shared data. Different colors are variable data. Ice tea and mineral water are two different types. Finally, len is used to calculate the length of the objpool to determine the number of classes. The total number of objects is 2.
The complete code is as follows:

class BottledWater(object):
    objpool = dict()#记录生成对象
    
    def show(self, color):#显示一下颜色
        print(self.name,'颜色',color)

    def __new__(cls, type):# 使用new 初始化在实例化之前
        obj_ = cls.objpool.get(type, None)#没有找到对象就实例化
        if obj_ == None:
            obj_ = object.__new__(cls)
            cls.objpool[type] = obj_
            obj_.name = type
        return obj_

t1 = BottledWater("矿泉水")
t1.show('红色')
t2 = BottledWater("矿泉水")
t2.show('蓝色')
t3 = BottledWater("矿泉水")
t3.show('绿色')
print('\n')
t1_ = BottledWater("冰红茶")
t1_.show('红色')
t2_ = BottledWater("冰红茶")
t2_.show('蓝色')
t3_ = BottledWater("冰红茶")
t3_.show('绿色')

print('对象一共有:',len(BottledWater.objpool))

Guess you like

Origin blog.csdn.net/A757291228/article/details/107130552