0%

享元模式

背景

在RGP射击游戏中,通常有大量的子弹、导弹、碎片等对象被生成,如果每个对象都有一份对立的属性值,那么一旦游戏运行起来,内存很快就会被消耗完。但是其实这些对象很多的属性大多情况下都是相同的,这里就可以将这些共同的属性只保留一份。这时候就可以使用享元模式。

享元模式简介

享元模式放弃了在每个对象中保存所有数据的方式, 通过共享多个对象所共有的相同状态, 让你能在有限的内存容量中载入更多对象。享元模式也叫缓存模式

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <string>
#include <map>

class Color;
class Texture;
class Canvas;

class TreeType {
private:
std::string name;
Color color;
Texture texture;
public:
TreeType(const std::string & name, const Color & color, const Texture & texture):
name(name), color(color), texture(texture) {}
void draw(Canvas & convas, float x, float y) {}
};

class Tree {
private:
float x, y;
const TreeType & treeType;
public:
Tree(float x, float y, TreeType & treeType): x(x), y(y), treeType(treeType) {}

virtual void draw(Canvas & canvas) {
this.treeType->draw(canvas, x, y);
}
};


class TreeTypeFactory {
private:
std::map<std::string, TreeType> treeTypes;
TreeTypeFactory() = default;
static TreeTypeFactory _instance;
public:
static TreeTypeFactory & shared();

TreeType & getTreeType(const std::string & name, const Color & color, const Texture & texture) {
//if name not in this.treeTypes, create a tree type else return treeTypes[name]
}
};

class Forest {
private:
std::vector<Tree *> trees;
public:
planeTree(float x, float y, const std::string & treeTypeName, const Color & color, const Texture & texture) {
TreeType & treeType = TreeTypeFactory.shared().getTreeType(treeTypeName, color, texture);
Tree * tree = new Tree(x, y, treeType);
this->trees.push_back(tree);
}

virtual void draw(Canvas & canvas) {
for (auto tree : trees) {
tree->draw();
}
}
};

在上面的示例中,我们需要在画布中渲染一个森林,森林是由Forest类表示的,一个森林由数百万个树对象构成,树类用Tree表示,对于同一类Tree的不同对象,除了坐标x、y不同之外,使用的颜色,贴纸都一样,因此将颜色,贴纸数据都放到一个享元对象中,享元类用TreeType表示。之后每个Tree对象都持有一个享元对象的引用。一般一类树都引用同一个享元对象。

TreeTypeFactory用于享元对象的获取,如果之前享元对象不存在,则返回一个新的享元对象,如果享元对象存在,则直接返回。