享元模式通过共享内部状态减少内存开销,适用于大量相似对象场景。C++中以工厂管理可共享的内部状态(如样式),结合智能指针避免重复创建,外部状态(如内容)由客户端传入,实现高效复用与低内存消耗。

享元模式(Flyweight Pattern)是一种结构型设计模式,主要用于减少创建大量相似对象时的内存开销。它通过共享已有的对象来避免重复创建,特别适用于系统中存在大量细粒度、相似对象的场景,比如文本编辑器中的字符格式、图形系统中的图元样式等。
C++ 实现享元模式的核心思路是:将对象中可共享的“内部状态”与不可共享的“外部状态”分离。内部状态存储在享元对象中,被多个上下文共享;外部状态则由客户端传入,不保存在享元内部。
享元模式通常包含以下几个部分:
假设我们要实现一个文本编辑器,每个字符都有字体、颜色等属性。如果每个字符都独立保存这些信息,内存消耗巨大。使用享元模式,我们可以共享相同的格式设置。
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <string>
#include <map>
#include <memory>
// 抽象享元类
class CharacterStyle {
public:
virtual ~CharacterStyle() = default;
virtual void display(const std::string& content) const = 0;
};
// 具体享元类
class ConcreteCharacterStyle : public CharacterStyle {
private:
std::string font;
int size;
std::string color;
public:
ConcreteCharacterStyle(const std::string& f, int s, const std::string& c)
: font(f), size(s), color(c) {}
void display(const std::string& content) const override {
std::cout << "内容: " << content
<< " [字体: " << font
<< ", 大小: " << size
<< ", 颜色: " << color << "]\n";
}
};
// 享元工厂
class StyleFactory {
private:
std::map<std::string, std::shared_ptr<CharacterStyle>> styles;
// 生成唯一 key 表示一种样式
std::string makeKey(const std::string& font, int size, const std::string& color) {
return font + "-" + std::to_string(size) + "-" + color;
}
public:
std::shared_ptr<CharacterStyle> getStyle(
const std::string& font, int size, const std::string& color) {
std::string key = makeKey(font, size, color);
if (styles.find(key) == styles.end()) {
styles[key] = std::make_shared<ConcreteCharacterStyle>(font, size, color);
}
return styles[key];
}
};
客户端使用方式:
int main() {
StyleFactory factory;
auto style1 = factory.getStyle("宋体", 12, "黑色");
auto style2 = factory.getStyle("宋体", 12, "黑色"); // 会复用 style1
auto style3 = factory.getStyle("楷体", 14, "红色");
style1->display("Hello");
style2->display("World"); // 使用同一实例
style3->display("!");
// 验证是否为同一对象
std::cout << "style1 和 style2 是否相同: "
<< (style1.get() == style2.get() ? "是" : "否") << "\n";
return 0;
}
享元模式在 C++ 中有效支持大量细粒度对象的关键在于:
享元模式适合以下情况:
但也要注意:
以上就是C++怎么实现一个享元模式_C++运用共享技术有效支持大量细粒度对象的模式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号