大话设计模式之享元模式

享元模式是一种结构型设计模式,旨在有效地支持大量细粒度的对象共享,从而减少内存消耗和提高性能。

在享元模式中,对象分为两种:内部状态(Intrinsic State)和外部状态(Extrinsic State)。内部状态是对象可以共享的状态,它存储在享元对象内部,并且不会随着外部环境的改变而改变;外部状态是对象的外部环境可以变化的部分,它由客户端传递给享元对象,并且在享元对象之外维护。

享元模式的关键是使用共享对象来减少内存使用和提高性能。当需要创建新对象时,首先检查是否已经存在具有相同内部状态的对象,如果存在,则返回该对象的引用;如果不存在,则创建一个新对象并将其加入到共享池中,以便下次可以重复使用。

cpp 复制代码
#include <iostream>
#include <map>
#include <string>

// 抽象享元类
class Flyweight {
public:
    virtual ~Flyweight() {}
    virtual void operation(const std::string& unique_state) const = 0;
};

// 具体享元类
class ConcreteFlyweight : public Flyweight {
public:
    ConcreteFlyweight(const std::string& shared_state) : shared_state_(shared_state) {}

    void operation(const std::string& unique_state) const override {
        std::cout << "ConcreteFlyweight: Shared state (" << shared_state_ << "), Unique state (" << unique_state << ")\n";
    }

private:
    std::string shared_state_;
};

// 享元工厂类
class FlyweightFactory {
public:
    Flyweight* getFlyweight(const std::string& shared_state) {
        if (flyweights_.find(shared_state) == flyweights_.end()) {
            flyweights_[shared_state] = new ConcreteFlyweight(shared_state);
        }
        return flyweights_[shared_state];
    }

    ~FlyweightFactory() {
        for (auto it = flyweights_.begin(); it != flyweights_.end(); ++it) {
            delete it->second;
        }
        flyweights_.clear();
    }

private:
    std::map<std::string, Flyweight*> flyweights_;
};

int main() {
    FlyweightFactory factory;

    Flyweight* flyweight1 = factory.getFlyweight("shared_state_1");
    flyweight1->operation("unique_state_1");

    Flyweight* flyweight2 = factory.getFlyweight("shared_state_2");
    flyweight2->operation("unique_state_2");

    Flyweight* flyweight3 = factory.getFlyweight("shared_state_1");
    flyweight3->operation("unique_state_3");



    return 0;
}

/*
在这个示例中,Flyweight 是抽象享元类,定义了操作接口 operation()。
ConcreteFlyweight 是具体享元类,实现了抽象享元类的接口。
FlyweightFactory 是享元工厂类,负责创建和管理享元对象。

在 main() 函数中,我们使用享元工厂来获取享元对象,并且重复使用了具有相同内部状态的对象。

*/

觉得有帮助的话,打赏一下呗。。

相关推荐
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
烛阴1 天前
【TS 设计模式完全指南】懒加载、缓存与权限控制:代理模式在 TypeScript 中的三大妙用
javascript·设计模式·typescript
李广坤1 天前
工厂模式
设计模式
幂简集成explinks2 天前
e签宝签署API更新实战:新增 signType 与 FDA 合规参数配置
后端·设计模式·开源
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
努力也学不会java2 天前
【设计模式】抽象工厂模式
java·设计模式·oracle·抽象工厂模式
青草地溪水旁2 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁2 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
Magnetic_h3 天前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa