设计模式9——组合模式
组合模式中,整体和部分可以同等看待,基类设定一个节点接口,可以派生出叶子节点和非叶子节点。叶子节点不能添加节点,非叶子节点可以添加,组成一个典型的树形结构。
组合模式在游戏引擎的渲染树中应用很广泛。
Composite.h内容
1 #ifndef Composite_H_H 2 #define Composite_H_H 3 4 #include<iostream> 5 #include<vector> 6 using namespace std; 7 8 class Composite 9 { 10 public: 11 Composite(string str) : name(str) {} 12 virtual ~Composite() {} 13 virtual void add(Composite *composite) = 0; 14 virtual void display() = 0; 15 protected: 16 string name; 17 }; 18 19 class Leaf : public Composite 20 { 21 public: 22 Leaf(string str) : Composite(str) {} 23 virtual void add(Composite *composite) {} 24 virtual void display() { cout << name << " "; } 25 private: 26 27 }; 28 29 class Component : public Composite 30 { 31 public: 32 Component(string str) : Composite(str) { } 33 virtual void add(Composite *composite) { vecChildren.push_back(composite); } 34 virtual void display(){ 35 cout << name << " " << endl; 36 for(size_t i=0; i<vecChildren.size(); ++i){ 37 vecChildren[i]->display(); 38 } 39 } 40 private: 41 vector<Composite*> vecChildren; 42 }; 43 44 void CompositeTest() 45 { 46 Composite *com1 = new Component("A"); 47 Composite *leaf1 = new Leaf("B"); 48 Composite *leaf2 = new Leaf("C"); 49 com1->add(leaf1); 50 com1->add(leaf2); 51 52 Composite *com2 = new Component("D"); 53 Composite *leaf4 = new Leaf("E"); 54 Composite *leaf5 = new Leaf("F"); 55 com2->add(leaf4); 56 com2->add(leaf5); 57 58 com1->add(com2); 59 60 com1->display(); 61 62 } 63 64 #endif
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!