python设计模式(享元模式)

来源:互联网 发布:linux主目录是什么 编辑:程序博客网 时间:2024/06/02 00:30

学习版本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: hello2show the string: hello1show the string: hello33


原创粉丝点击