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

享元模式(Flyweight Pattern)是一种结构型设计模式,主要用于减少创建大量相似对象时的内存开销。它的核心思想是:通过共享尽可能多的数据来支持大量细粒度的对象。在C++中,实现享元模式的关键在于分离**内部状态(Intrinsic State)** 和 **外部状态(Extrinsic State)**。
内部状态是可共享的、不会随环境改变的状态;外部状态是依赖上下文、不可共享的部分,通常由客户端传入。
享元模式的基本结构
一个典型的享元模式包含以下几个部分:
Flyweight(抽象享元类):定义接口,接受外部状态作为参数。ConcreteFlyweight(具体享元类):实现 Flyweight 接口,并存储内部状态。UnsharedConcreteFlyweight(非共享具体享元):不需要共享的对象,可选。FlyweightFactory(享元工厂):负责管理享元对象,确保共享对象能被正确复用。
C++ 实现示例
假设我们要绘制森林中的树,每棵树有类型(种类、颜色、纹理)和位置(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> treeTypes;
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(name, color, texture));return treeTypes.back().get();}};
上面代码中我们省略了 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> trees;TreeFactory factory;
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(x, y, type));}
void draw() const { for (const auto& tree : trees) { tree->draw(); }}
};
使用示例
int main() { Forest forest;
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 NeedleDrawing Pine tree at (3,4) with color Green and texture NeedleDrawing Oak tree at (5,6) with color Brown and texture Broad
虽然创建了三棵树,但只生成了两个 TreeType 对象,“Pine” 类型被成功复用。
关键点总结
实现享元模式需要注意以下几点:
把不变的状态提取出来作为享元对象,通常是构造参数固定的资源。享元对象必须是不可变的或线程安全的,否则共享会出问题。工厂类应保证相同参数只创建一次享元对象,可用哈希表优化查找。外部状态不能保存在享元中,必须在方法调用时传入。
基本上就这些。享元模式适合对象数量巨大且存在大量重复数据的场景,比如文字编辑器中的字符格式、游戏中的粒子系统或地图元素。合理使用能显著降低内存占用。
以上就是C++怎么实现一个享元模式(Flyweight)_C++设计模式与享元模式实现的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1485040.html
微信扫一扫
支付宝扫一扫