当前位置: 首页> 教育> 高考 > 设计模式 之 —— 组合模式

设计模式 之 —— 组合模式

时间:2025/8/24 18:47:51来源:https://blog.csdn.net/Jilit_jilit/article/details/141170896 浏览次数:0次

目录

什么是组合模式?

定义

特点

结构

组合模式(java代码示例)

首先定义接口 

定义叶节点(Leaf类)

定义容器节点(Composite类)

测试类:

树形图

运行结果:

组合模式的优缺点

优点:

缺点:


什么是组合模式?

定义

组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。

特点

树状层次结构:可以形成一个树的层次结构,很好地反映部分-整体的关系

单一接口:组合模式为所有的组件(叶子或容器)定义了一个统一的接口

动态组合:客户端可以在运行时动态地添加或删除组件(叶子或容器)

结构

  • Component接口:定义了所有对象必须实现的操作。
  • Leaf类:实现Component接口,代表树中的叶子节点。
  • Composite类:同样实现Component接口,并包含其他Component对象的集合。

组合模式(java代码示例)

首先定义接口 

interface Component {//定义了所有对象必须实现的操作void operation();
}

定义叶节点(Leaf类)

// 叶节点
class Leaf implements Component {private String name;public Leaf(String name) {this.name = name;}public void operation() {System.out.println("叶节点 " + name + " 执行操作");}
}

(实现Component接口)

定义容器节点(Composite类)

// 容器节点
class Composite implements Component {private String name;private List<Component> children = new ArrayList<>();public Composite(String name) {this.name = name;}public void add(Component component) {children.add(component);}public void remove(Component component) {children.remove(component);}public void operation() {System.out.println("容器节点 "+ name +" 执行操作:");for (Component component : children) {component.operation();}}
}

(实现Component接口)

测试类:

//测试类
public class CompositePatternDemo {public static void main(String[] args) {// 创建叶节点Component leaf1 = new Leaf("Leaf 1");Component leaf2 = new Leaf("Leaf 2");// 创建容器节点Composite composite = new Composite("总容器");//把叶子节点添加到容器节点(也可把其它容器添加到容器节点)composite.add(leaf1);composite.add(leaf2);Component leaf3 = new Leaf("Leaf 3");Component leaf4 = new Leaf("Leaf 4");Composite composite2 = new Composite("小容器");composite2.add(leaf3);composite2.add(leaf4);composite.add(composite2);//composite.remove(composite2);//移除// 执行操作composite.operation();}
}
树形图

我写的上述代码的树形结构图如下:

运行结果:

组合模式的优缺点

优点:

客户端可以一致地处理单个对象和组合对象,不需要关心它们的具体类型(简化了客户端代码的编写和维护)

可以很容易地向树状结构中添加新的组件,而不需要修改现有的代码(提高了系统的灵活性和可扩展性)

部分-整体层次结构:更容易反映现实中事物的自然层次(有助于开发更加贴近现实的系统)

客户端不需要关心对象的组合结构,可以直接调用方法来操作树状结构中的元素(降低了客户端的复杂性)

缺点:

增加了设计的复杂度(组合模式需要引入许多新的类,如抽象构件、叶子和容器)

可能限制组件的类型:组合模式要求组件和叶子节点具有相同的接口,这可能会限制组件的类型(例如,所有的组件都必须实现相同的操作,即使某些组件并不需要这些操作)

对于复杂的树状结构,遍历操作的复杂度会较高。

组合模式的一个优点和缺点都是透明性:客户端不需要知道它是在处理单个对象(Leaf)还是组合对象(Composite)
但是,这种透明性也可能带来问题:客户端无法区分单个对象和组合对象,可能会导致误用或错误使用。

关键字:设计模式 之 —— 组合模式

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: