两种语言实现设计模式(C++和Java)(十二:组合模式)
组合模式,将对象组合成属性结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。其UML图如下:
主要解决:它在我们树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以像处理简单元素一样处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦。
如何解决:树枝和树叶实现统一接口,树枝内部组合该接口。
关键代码:树枝内部组合该接口,并且含有内部属性list,里面放Component。
可以用组合模式来表述大学里学院之间的关系,例如工程学院包含机械学院和计算机学院,代码如下:
C++代码:
1 #include <iostream> 2 #include <vector> 3 #include <list> 4 5 using namespace std; 6 7 class College{ 8 protected: 9 string name; 10 public: 11 College(string _name){ 12 name = _name; 13 } 14 virtual void add(College* p) = 0; 15 virtual void remove(string name) = 0; 16 virtual void display() = 0; 17 string getName(){ 18 return this->name; 19 } 20 }; 21 22 class ConcreteCollege: public College{ 23 public: 24 ConcreteCollege(string _name): College(_name){} 25 void add(College* p){ 26 shared_ptr<College> temp(p); 27 listCollege.push_back(temp); 28 } 29 void remove(string name){ 30 auto it = listCollege.begin(); 31 for(it; it != listCollege.end(); it++){ 32 shared_ptr<College> temp(*it); 33 string strName = temp->getName(); 34 if(name == strName){ 35 listCollege.erase(it); 36 } 37 } 38 } 39 void display(){ 40 cout << this->getName()<< endl; 41 for (auto it = listCollege.begin(); it != listCollege.end(); it++){ 42 (*it)->display(); 43 } 44 } 45 private: 46 vector<shared_ptr<College>> listCollege; 47 }; 48 49 int main() 50 { 51 College *c1 = new ConcreteCollege("Engineering College"); 52 c1->add(new ConcreteCollege("Mechanical College")); 53 c1->add(new ConcreteCollege("Computer College")); 54 c1->display(); 55 return 0; 56 }
这里使用了shared_ptr智能指针避免delete带来的麻烦
Java代码
1 public interface ICollege { 2 public void add(ICollege iCollege); 3 public void delete(ICollege iCollege); 4 public void display(); 5 } 6 7 public class College implements ICollege { 8 9 private String name; 10 11 private ArrayList<ICollege> listCollege; 12 13 public String getName(){return this.name;} 14 15 public College(String name){ 16 listCollege = new ArrayList<ICollege>(); 17 this.name = name; 18 } 19 20 public void add(ICollege iCollege) { 21 listCollege.add(iCollege); 22 } 23 24 public void delete(ICollege iCollege) { 25 listCollege.remove(iCollege); 26 } 27 28 public void display() { 29 System.out.println(name); 30 for (ICollege iCollege: 31 listCollege) { 32 iCollege.display(); 33 } 34 } 35 } 36 37 public class Main { 38 public static void main(String[] args) { 39 ICollege c = new College("Engineering College"); 40 c.add(new College("Mechanical College")); 41 c.add(new College("Computer College")); 42 c.display(); 43 } 44 }
分类:
设计模式
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具