-
Notifications
You must be signed in to change notification settings - Fork 0
/
Composite.cpp
75 lines (63 loc) · 1.8 KB
/
Composite.cpp
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
70
71
72
73
74
75
/*
客户端可以一致地使用一个组合结构或其中单个对象,不必关心处理的是单个对象还是整个组合结构,简化了客户端代码。
*/
#include <iostream>
#include <list>
#include <string>
using namespace std;
class Component{
public:
virtual void print(int depth) = 0;
virtual void add(Component* c) = 0;
};
class Folder : public Component{
public:
void add(Component* c){
entry.push_front(c);
}
void print(int depth){
string prefix = ">";
prefix.append(depth, '-');
cout << prefix << "这是一个文件夹:" << endl;
for(list<Component*>::iterator it = entry.begin(); it!=entry.end(); ++it){
(*it)->print(depth+2);
}
}
private:
list<Component*> entry;
};
class File : public Component{
public:
void print(int depth){
string prefix = ">";
prefix.append(depth, '-');
cout << prefix << "这只是一个文件" << endl;
}
void add(Component* c){
cout << "错误使用!" << endl;
}
};
int main(){
Component* root = new Folder();
Component* file = new File();
Component* folder1 = new Folder();
Component* file11 = new File();
Component* file12 = new File();
Component* folder2 = new Folder();
Component* file21 = new File();
Component* file22 = new File();
Component* folder22 = new Folder();
Component* file212 = new File();
Component* file222 = new File();
folder1->add(file11);
folder1->add(file12);
root->add(folder1);
folder2->add(file21);
folder2->add(file22);
root->add(folder2);
folder2->add(folder22);
folder22->add(file212);
folder22->add(file222);
root->add(file);
root->print(1);
}