Flyweight

博客介绍了处理对象的好处,可减少需处理的对象数量,若对象持久化还能降低对内存和存储设备的需求。同时说明了适用场景,如应用使用大量对象、因对象数量多导致存储成本高,且应用不依赖对象标识。

Benefits:
• It reduces the number of objects to deal with.
• It reduces the amount of memory and storage devices required if the objects are persisted.

Applicable Scenarios:
• An application uses a considerable number of objects.
• The storage costs are high because of the quantity of objects.
• The application does not depend on object identity.

### Flyweight设计模式的概念 Flyweight设计模式是一种结构型设计模式,其核心目标是通过共享对象来减少内存消耗。这种模式特别适用于需要创建大量相似对象的场景,并且这些对象的状态变化很小,可以实现多次复用[^1]。Flyweight模式通过将对象的内部状态(intrinsic state)与外部状态(extrinsic state)分离,使得多个对象可以共享相同的内部状态,而外部状态则由客户端负责管理[^2]。 --- ### Flyweight设计模式的实现 Flyweight模式的实现通常包括以下几个关键角色: 1. **Flyweight(享元类)**:表示那些实例会被共享的类,包含内部状态。 2. **FlyweightFactory(享元工厂类)**:负责生成和管理Flyweight对象,确保共享对象的唯一性。 3. **Client(客户端)**:使用FlyweightFactory生成Flyweight对象,并提供外部状态以完成具体操作。 以下是一个C++实现Flyweight模式的示例代码[^2]: ```cpp #include <iostream> #include <string> #include <unordered_map> class Flyweight { public: virtual void operation(const std::string& extrinsicState) = 0; virtual ~Flyweight() {} }; class ConcreteFlyweight : public Flyweight { private: std::string intrinsicState; public: ConcreteFlyweight(const std::string& state) : intrinsicState(state) {} void operation(const std::string& extrinsicState) override { std::cout << "Intrinsic State = " << intrinsicState << ", Extrinsic State = " << extrinsicState << std::endl; } }; class FlyweightFactory { private: std::unordered_map<std::string, Flyweight*> flyweights; public: Flyweight* getFlyweight(const std::string& key) { if (flyweights.find(key) == flyweights.end()) { flyweights[key] = new ConcreteFlyweight(key); } return flyweights[key]; } ~FlyweightFactory() { for (auto& pair : flyweights) { delete pair.second; } } }; int main() { FlyweightFactory factory; Flyweight* f1 = factory.getFlyweight("A"); f1->operation("Client State A"); Flyweight* f2 = factory.getFlyweight("B"); f2->operation("Client State B"); Flyweight* f3 = factory.getFlyweight("A"); f3->operation("Client State A Reuse"); return 0; } ``` 在上述代码中,`ConcreteFlyweight` 类封装了对象的内部状态,而外部状态由客户端通过 `operation` 方法传递。`FlyweightFactory` 负责管理共享对象的创建和复用[^2]。 --- ### Flyweight设计模式的应用场景 Flyweight模式适用于以下场景: 1. **需要创建大量相似对象的场景**:例如文档编辑软件中的样式模板[^5],每个标题或段落样式可以作为一个共享的享元对象。 2. **需要优化内存使用的场景**:当系统中存在大量细粒度对象时,可以通过共享公共信息来减少内存消耗[^3]。 3. **对象状态变化较小的场景**:如果对象的状态大部分是固定的,只有少部分需要动态变化,则适合使用Flyweight模式[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值