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

Python design pattern structural pattern shared meta pattern

編輯:Python

Catalog

List of articles

  • Catalog
  • The flyweight pattern
  • Application scenarios
  • Code example

The flyweight pattern

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 :

  1. Intrinsic state : Stored in Xiangyuan , It doesn't change with the environment , It can be shared .
  2. Extrinsic state : It can't be shared , It changes with the environment , Therefore, the intrinsic state is maintained by the client ( Because changes in the environment are caused by the client ).

Application scenarios

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 .

Code example

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

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