Flyweight模式,运用共享技术有效地支持大量细粒度的对象。在游戏开发中,享元模式的一个典型应用是森林,森林中有大量的树木,可以共用相同的mesh、树干和树叶纹理,然后利用GPU Instance成千上万颗树。
class Mesh;
class Texture;
class Color;
class TreeModel {
private:
Mesh* mesh; // 树mesh数据
Texture* texBark; // 树干纹理
Texture* texLeaf; // 树叶纹理
}
class Tree {
private:
TreeModel* model;
float height;
float thickness;
Color colorBark;
Color colorLeaf;
}
// test
void Test() {
TreeModel* treeModel = new TreeModel();
// set mesh, bark texture, leaf texture
List<Tree> list = new List<Tree>();
for (int i = 0; i = 1000; i++) {
Tree* tree = new Tree();
// set TreeModel, height, thickness, ...
}
// todo ... destroy
}
PS. 我的设计模式系列blog,《设计模式》专栏,通过简单的示例演示设计模式,对于初学者很容易理解入门。深入学习请看GoF的《设计模式》。