享元模式通过共享内部状态减少内存开销,分离可变外部状态与不可变内部状态。示例中TreeType存储种类、颜色、纹理等内部状态,由TreeFactory管理复用;位置作为外部状态在draw时传入。Forest中种植多棵树,相同类型的树共享同一TreeType实例,避免重复创建,显著降低内存使用,适用于对象数量庞大且存在重复数据的场景。

享元模式(Flyweight Pattern)是一种结构型设计模式,主要用于减少创建大量相似对象时的内存开销。它的核心思想是:通过共享尽可能多的数据来支持大量细粒度的对象。在C++中,实现享元模式的关键在于分离**内部状态(Intrinsic State)** 和 **外部状态(Extrinsic State)**。
内部状态是可共享的、不会随环境改变的状态;外部状态是依赖上下文、不可共享的部分,通常由客户端传入。
一个典型的享元模式包含以下几个部分:
假设我们要绘制森林中的树,每棵树有类型(种类、颜色、纹理)和位置(X, Y)。其中“种类、颜色、纹理”是内部状态,可以共享;“位置”是外部状态,每次调用时传入。
立即学习“C++免费学习笔记(深入)”;
// TreeType.h - 共享的内部状态 class TreeType { private: std::string name; std::string color; std::string texture;
public: TreeType(const std::string& n, const std::string& c, const std::string& t) : name(n), color(c), texture(t) {}
void draw(int x, int y) const {
std::cout << "Drawing " << name << " tree at (" << x << "," << y
<< ") with color " << color << " and texture " << texture << "\n";
}};
// TreeFactory.h - 享元工厂
class TreeFactory {
private:
std::vector<std::unique_ptr
public:
TreeType* getTreeType(const std::string& name, const std::string& color, const std::string& texture) {
for (const auto& tt : treeTypes) {
if (tt->getName() == name && tt->getColor() == color && tt->getTexture() == texture) {
return tt.get();
}
}
// 没找到就创建新的
treeTypes.push_back(std::make_unique
上面代码中我们省略了 TreeType 的 getter 方法,实际使用中需要添加 getName(), getColor(), getTexture() 等函数用于比较。
// Tree.h - 外部接口,使用享元 class Tree { private: int x, y; // 外部状态 TreeType* type; // 内部状态(共享)
public: Tree(int x, int y, TreeType* type) : x(x), y(y), type(type) {}
void draw() const {
type->draw(x, y);
}};
// Forest.h - 容器类
class Forest {
private:
std::vector<std::unique_ptr
public:
void plantTree(int x, int y, const std::string& name, const std::string& color, const std::string& texture) {
TreeType* type = factory.getTreeType(name, color, texture);
trees.push_back(std::make_unique
void draw() const {
for (const auto& tree : trees) {
tree->draw();
}
}};
forest.plantTree(1, 2, "Pine", "Green", "Needle"); forest.plantTree(3, 4, "Pine", "Green", "Needle"); // 复用同一类型 forest.plantTree(5, 6, "Oak", "Brown", "Broad"); forest.draw(); return 0;
}
输出结果:
Drawing Pine tree at (1,2) with color Green and texture Needle Drawing Pine tree at (3,4) with color Green and texture Needle Drawing Oak tree at (5,6) with color Brown and texture Broad
虽然创建了三棵树,但只生成了两个 TreeType 对象,“Pine” 类型被成功复用。
实现享元模式需要注意以下几点:
基本上就这些。享元模式适合对象数量巨大且存在大量重复数据的场景,比如文字编辑器中的字符格式、游戏中的粒子系统或地图元素。合理使用能显著降低内存占用。
以上就是C++怎么实现一个享元模式(Flyweight)_C++设计模式与享元模式实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号