模板方法允许程序员实现一种算法骨架,在具体算法中实现骨架中的每个具体步骤而不改变骨架本身。

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
class GameAI {
public:
std::vector<Structure*> builtStructures;
void turn() {
collectResources();
buildStructures();
buildUnits();
attack();
}
void collectResources() {
for (Structure* s: builtStructures) {
s->collect();
}
}
virtual buildStructures() = 0;
virtual buildUnits() = 0;
void attack() {
Enemy* e = closestEnemy();
Map* m = getMap();
if (e == nullptr) sendScouts(m->center);
else sendWarriors(e->position);
}
virtual sendScouts(Coords pos) = 0;
virtual sendWarriors(Coords pos) = 0;
};

class OrcsAI: public GameAI {
void buildStructures() override {
if (resourceAvailable()) {
// build things
}
}
void buildUnits() override {
// build some units
}
// also implement sendScouts and sendWarriors
};

class MonsterAI: public GameAI {
void collectResources() {
return; // monsters don't collect resources
}
void buildStructures() {
return; // monsters don't build structures
}
void buildUnits() {
return; // monsters don't build units
}
}