学习版本3.5.2
享元模式的概念:在一个系统中如果有多个相同的对象,那么只共享一份,不必每一个都去实例化一个对象。像python中的数字变量就是用的享元模式。
写一个例子,用享元对象去存字符串,在享元对象的工厂中包涵了享元对象池。
class Flyweight(object):
def __init__(self, str):
self.str = str
def display(self):
print("show the string: " + self.str)
class FlyweightFactory(object):
def __init__(self):
self.flyweights = {}
def getFlyweight(self, obj):
flyweight = self.flyweights.get(obj)
if flyweight == None:
flyweight = Flyweight(str(obj))
self.flyweights[obj] = flyweight
return flyweight
def showFlyweights(self):
for i in self.flyweights:
self.flyweights[i].display()
print(len(self.flyweights))
if __name__ == "__main__":
flyweightfactory = FlyweightFactory()
fly1 = flyweightfactory.getFlyweight("hello1")
fly2 = flyweightfactory.getFlyweight("hello1")
fly3 = flyweightfactory.getFlyweight("hello2")
fly4 = flyweightfactory.getFlyweight("hello2")
fly5 = flyweightfactory.getFlyweight("hello3")
flyweightfactory.showFlyweights()
运行结果
show the string: hello2
show the string: hello1
show the string: hello3
3