...

Python设计模式-11-享元模式

享元模式是一种结构型设计模式,它通过共享对象来减少内存使用和对象创建的数量。享元模式通常包括以下几个角色:

  • 享元工厂(Flyweight Factory):负责创建和管理享元对象。
  • 享元(Flyweight):表示共享的对象,包含内部状态和外部状态。
  • 内部状态(Intrinsic State):存储在享元对象内部的状态,不会随着外部环境的改变而改变。
  • 外部状态(Extrinsic State):存储在享元对象外部的状态,会随着外部环境的改变而改变。

下面是一个简单的 Python 示例,演示了如何使用享元模式共享对象:

class Flyweight:
    def operation(self, extrinsic_state):
        pass

class ConcreteFlyweight(Flyweight):
    def __init__(self, intrinsic_state):
        self.intrinsic_state = intrinsic_state

    def operation(self, extrinsic_state):
        print(f'ConcreteFlyweight: Intrinsic state is {self.intrinsic_state}, extrinsic state is {extrinsic_state}.')

class FlyweightFactory:
    def __init__(self):
        self.flyweights = {}

    def get_flyweight(self, intrinsic_state):
        if intrinsic_state not in self.flyweights:
            self.flyweights[intrinsic_state] = ConcreteFlyweight(intrinsic_state)
        return self.flyweights[intrinsic_state]

factory = FlyweightFactory()

flyweight1 = factory.get_flyweight('state1')
flyweight1.operation('extrinsic_state1')

flyweight2 = factory.get_flyweight('state2')
flyweight2.operation('extrinsic_state2')

flyweight3 = factory.get_flyweight('state1')
flyweight3.operation('extrinsic_state3')

print(flyweight1 is flyweight3)

在上面的示例中,我们定义了一个享元 Flyweight,它表示共享的对象,包含内部状态和外部状态。然后,我们定义了一个具体享元 ConcreteFlyweight,它实现了 Flyweight 接口,并包含内部状态。接下来,我们定义了一个享元工厂 FlyweightFactory,它负责创建和管理享元对象。

posted @ 2023-06-16 18:31  韩志超  阅读(84)  评论(0编辑  收藏  举报