Enjoying yuan , Can be understood as Python The metaclass in 、 The smallest granularity class , When there are a large number of similar objects in the system , You can choose the sharing mode to improve resource utilization .
Xiangyuan has two states :
If an application uses a large number of objects , When these objects cause a lot of storage overhead, you can consider whether you can use the meta sharing mode .
for example : If you find that a large number of fine-grained instances of an object are generated , And these examples are basically the same except for a few parameters , If you move those shared parameters outside the class , Pass them in at method call time , By sharing a large number of single instances .
class FlyweightBase:
""" Shared element base class """
def offer(self):
pass
class Flyweight(FlyweightBase):
""" Shared metaclass """
def __init__(self, name):
self.name = name
def get_price(self, price):
print(' The product type :{} details :{}'.format(self.name, price))
class FactoryFlyweight:
""" Xiangyuan factory """
def __init__(self):
self.product = {
}
def Getproduct(self, key):
if not self.product.get(key, None):
self.product[key] = Flyweight(key)
return self.product[key]
if __name__ == '__main__':
test = FactoryFlyweight()
A = test.Getproduct(" High-end ")
A.get_price(" Perfume :80")
B = test.Getproduct(" High-end ")
B.get_price(" The mask :800")