美文网首页
Python享元模式

Python享元模式

作者: 虾想家 | 来源:发表于2017-03-19 13:41 被阅读86次

    享元模式,对可以共享的属性对象进行共享,无法共享的属性独立存储。

    class Obj:
        def __init__(self, value):
            self.content = value
    
        def __str__(self):
            return self.content
    
    
    class Share(object):
        def __init__(self):
            super().__init__()
            self.dct = {}
    
        def __getitem__(self, item):
            return self.dct.get(item, None)
    
        def __setitem__(self, key, value):
            self.dct[key] = value
    
    
    def main():
        share = Share()
        share['one'] = Obj("a")
        share['two'] = Obj("b")
        share['one'] = Obj("c")
        one = share['one']
        print(str(one))
    
    
    if __name__ == '__main__':
        main()
    

    相关文章

      网友评论

          本文标题:Python享元模式

          本文链接:https://www.haomeiwen.com/subject/jzypnttx.html