软件设计⑩|组合模式
一、效果如下:
二、类图如下:
三、代码如下:
1 #include <iostream> 2 #include <string> 3 #include <list> 4 using namespace std; 5 6 class AbstractFile 7 { 8 protected: 9 string name; 10 public: 11 AbstractFile(string name) :name(name) {} 12 virtual void AddFile(AbstractFile* file) {} 13 virtual void RemoveFile(AbstractFile* file) {} 14 virtual void GetChild(int depth) {} 15 }; 16 17 class File : public AbstractFile 18 { 19 public: 20 File(string name) :AbstractFile(name) {} 21 void AddFile(AbstractFile* file) 22 { 23 cout << "该文件不支持添加节点操作" << endl; 24 } 25 void RemoveFile(AbstractFile* file) 26 { 27 cout << "该文件不支持移除节点操作" << endl; 28 } 29 void GetChild(int depth) 30 { 31 string _tmpstring(depth, '-'); 32 cout << _tmpstring << name << endl; 33 } 34 }; 35 36 class Folder :public AbstractFile 37 { 38 private: 39 list<AbstractFile*> _list; 40 public: 41 Folder(string name) :AbstractFile(name) {} 42 void AddFile(AbstractFile* file) 43 { 44 _list.push_back(file); 45 } 46 void RemoveFile(AbstractFile* file) 47 { 48 _list.remove(file); 49 } 50 void GetChild(int depth) 51 { 52 string tmpstring(depth, '-'); 53 cout << tmpstring << name << endl; 54 list<AbstractFile*>::iterator iter = _list.begin(); 55 for (; iter != _list.end(); iter++) 56 { 57 (*iter)->GetChild(depth + 2); 58 } 59 } 60 }; 61 62 class Image :public AbstractFile 63 { 64 private: 65 list<AbstractFile*> _list; 66 public: 67 Image(string name) :AbstractFile(name) {} 68 void GetChild(int depth) 69 { 70 string _tmpstring(depth, '-'); 71 cout << _tmpstring << name << endl; 72 } 73 }; 74 75 class Txt :public AbstractFile 76 { 77 private: 78 list<AbstractFile*> _list; 79 public: 80 Txt(string name) :AbstractFile(name) {} 81 void GetChild(int depth) 82 { 83 string _tmpstring(depth, '-'); 84 cout << _tmpstring << name << endl; 85 } 86 }; 87 88 int main() 89 { 90 Folder* root = new Folder("root"); 91 Folder* user = new Folder("user"); 92 root->AddFile(user); 93 Folder* user1 = new Folder("user1"); 94 Image* image1 = new Image("image1"); 95 Txt* txt2 = new Txt("txt2"); 96 user->AddFile(user1); 97 user1->AddFile(image1); 98 user1->AddFile(txt2); 99 Folder* user2 = new Folder("user2"); 100 Image* image2 = new Image("image2"); 101 user->AddFile(user2); 102 user2->AddFile(image2); 103 Folder* bin = new Folder("bin"); 104 Txt* txt1 = new Txt("txt1"); 105 user->AddFile(bin); 106 bin->AddFile(txt1); 107 108 109 root->GetChild(1); 110 cout << endl; 111 112 delete root; 113 delete user; 114 delete user1; 115 delete user2; 116 delete bin; 117 delete image1; 118 delete image2; 119 delete txt1; 120 delete txt2; 121 122 system("pause"); 123 return 0; 124 }