设计模式-享元模式

Posted su-sir

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式-享元模式相关的知识,希望对你有一定的参考价值。

享元模式

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

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

例子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

以上是关于设计模式-享元模式的主要内容,如果未能解决你的问题,请参考以下文章

设计模式课程 设计模式精讲 13-1 享元模式coding

常用设计模式系列之——享元模式

11-享元(Flyweight)模式Ruby实现

23种设计模式之享元模式代码实例

深入理解设计模式-享元模式

深入理解设计模式-享元模式