现欲构造一个文件/目录树,采用组合(Composite)设计模式来设计,得到的类图如下:
C++代码为:
1 #include <list>
2 #include <iostream>
3 #include <string>
4
5 using namespace std;
6
7 class AbstractFile {
8 protected:
9 string name; /*文件或目录名*/
10 public:
11 void printName() {cout<<name<<endl;} /*打印文件或目录名称*/
12 virtual void addChild(AbstractFile *file)=0; /*给一个目录增加子目录或文件*/
13 virtual void removeChild(AbstractFile *file)=0; /*删除一个目录的子目录或文件*/
14 virtual list<AbstractFile *> *getChildren()=0; /*保存一个目录的子目录或文件*/
15 };
16
17 class File:public AbstractFile{
18 public:
19 File(string name) {this->name=name;}
20 void addChild(AbstractFile *file) {return;}
21 void removeChild(AbstractFile *file) {return;}
22 list<AbstractFile *> *getChildren() {return NULL;}
23 };
24
25 class Folder:public AbstractFile {
26 private:
27 list<AbstractFile *> childList; /*存储子目录或文件*/
28 public:
29 Folder(string name) {this->name=name;}
30 void addChild(AbstractFile *file) {childList.push_back(file);}
31 void removeChild(AbstractFile *file) {childList.remove(file);}
32 list<AbstractFile *> *getChildren() {return &childList;}
33 };
34
35 int main() {
36 AbstractFile *rootFolder=new Folder("c:\\");
37 AbstractFile *compositeFolder=new Folder("composite");
38 AbstractFile *WindowsFolder=new Folder("Windows");
39 AbstractFile *file=new File("TestComposite.C++");
40 rootFolder->addChild(compositeFolder);
41 rootFolder->addChild(WindowsFolder);
42 compositeFolder->addChild(file);
43 rootFolder->printName();
44 compositeFolder->printName();
45 WindowsFolder->printName();
46 file->printName();
47 return 0;
48 }