码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式-享元模式

时间:2020-03-22 21:17:19      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:col   weight   log   sdn   享元模式   内存   object   lock   状态   

享元模式

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

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

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

设计模式-享元模式

标签:col   weight   log   sdn   享元模式   内存   object   lock   状态   

原文地址:https://www.cnblogs.com/su-sir/p/12548292.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!