Python享元模式

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

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享元模式)