组合模式是一种树形结构,有两种重要节点:叶节点和组合节点。组合节点可以包含叶节点或子组合节点。但是无论叶节点还是组合节点,都有相同的接口,只不过叶节点执行具体的操作,而组合节点执行遍历,并将操作传递给子节点。

组合模式的树形结构有一些独特的优势,例如,你可以任意选择若干个子树,然后重新组合,成为一个新的树而不干扰现有的结构!

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
61
62
63
64
65
66
67
68
69
class Graphic {
public:
virtual void move(int x, int y) = 0;
virtual void draw(Canvas& c) const = 0;
virtual ~Graphic() {};
};

class Dot: public Graphic {
public:
int x_;
int y_;
Dot(int x, int y): x_(x), y_(y) {}
void move(int x, int y) {
x_ += x;
y_ += y;
}
void draw(Canvas& c) {
// draw dot on the canvas
}
};

class Circle: public Dot {
public:
int radius_;
Circle(int x, int y, int r): Dot(x, y), radius_(r) {}
void draw(Canvas& c) {
// draw a circle on the canvas
}
};

class CompoundGraphic: public Graphic {
public:
std::vector<Graphic*> children;
void add(Graphic* child) {
children.push_back(child);
}
void remove(Graphic* child) {
// delete from children
}
void move(int x, int y) {
for(int i = 0; i < children.size(); i++) {
children[i]->move(x, y);
}
}
void draw(Canvas& c) {
// for each child component, draw the component
// also draw the bounding boxes
}
};

class Editor {
public:
CompoundGraphic all_;
void load() {
all_ = CompoundGraphic();
all_.add(new Dot(1, 2));
all_.add(new Circle(1, 2, 3));
// ...
}
void groupSelected(std::vector<Graphic*>& arr) {
CompoundGraphic* group = new CompoundGraphic();
for (int i = 0; i < arr.size(); i++) {
group.add(arr[i]);
all_.remove(arr[i]);
}
all_.add(group);
all_.draw();
}
};

注意,上面的代码存在内存管理问题!只是一个示例!改成这样或许能够缓解内存管理问题:

1
2
3
void add(Graphic* child) {
children.push_back(std::unique_ptr<Graphic>(child));
}