设计模式-享元模式

享元模式

  定义:保证共享同一状态的对象可以同时使用该共享状态的内存

  作用:减少重复对象,节约系统资源

例子1:
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 = {}  # 使用字典kye的唯一性实现享元

    def getFlyweight(self, obj):
        flyweight = self.flyweights.get(obj)
        if flyweight == None:
            flyweight = Flyweight(str(obj))
            self.flyweights[obj] = flyweight

    def showFlyweights(self):
        for i in self.flyweights:
            self.flyweights[i].display()
        print(len(self.flyweights))


if __name__ == "__main__":
    flyweightfactory = FlyweightFactory()
    flyweightfactory.getFlyweight("hello1")
    flyweightfactory.getFlyweight("hello1")
    flyweightfactory.getFlyweight("hello2")
    flyweightfactory.getFlyweight("hello2")
    flyweightfactory.getFlyweight("hello3")

    flyweightfactory.showFlyweights()
    
结果:
"""
show the string: hello1
show the string: hello2
show the string: hello3
3
"""

参考:https://blog.csdn.net/u013346751/article/details/78426104

posted @ 2020-03-22 21:05  海澜时见鲸  阅读(87)  评论(0)    收藏  举报