组合模式(Composite Pattern)又叫作整体-部分(Part-Whole)模式,它的宗旨是通过将单个对象(叶子节点)和组合对象(树枝节点)用相同的接口进行表示,使得客户对单个对象和组合对象的使用具有一致性,属于结构型设计模式。
一颗树一般有三种节点
- 根节点
- 树干节点
- 叶子节点
根节点和树干节点本质上是一种数据类型。在组合模式中,把树干节点和叶子节点也视为是一种数据类型(实现同一个接口),在调用的时候不需要区分是树干节点还是叶子节点。
当子系统与其内各个对象层次呈树形结构时,可以使用组合模式让子系统内各个对象层次的行为操作具备一致性。当客户端使用该子系统内任意一个对象时,不用进行区分,直接使用通用操作即可,非常便捷。
场景:
- 树状结构
- 客户端可以忽略组合对象与单个对象的差异
树枝节点和叶子节点实现用一个接口或继承同一个基类
透明模式
Component中声明树干节点和根节点的方法,具体实现由子类重写,客户端无需区分树干节点和叶子节点
安全模式
Component中只声明公共的方法,子类各自声明自己的特有方法
接口定义职责分明,符合单一职责原则和接口隔离原则,但是客户端必须区分树干节点和叶子节点有些操作需要强制类型转换违背了依赖倒置原则
当系统绝大多数层次都具备想用的公共行为,使用透明模式,当各个层次差异较多或树枝节点层级相对稳定时使用安全模式
框架
HashMap的putAll
Mybatis的sqlNode
安全模式的demo
package com.company.composite;public abstract class Component {protected String name;public Component(String name) {this.name = name;}public abstract void op();}package com.company.composite;import java.util.ArrayList;import java.util.List;public class Composite extends Component {private List<Component> componentList;public Composite(String name) {super(name);this.componentList = new ArrayList<>();}@Overridepublic void op() {for(Component component : componentList){component.op();}}public void add(Component component){this.componentList.add(component);}public void remove(Component component){this.componentList.remove(component);}public void getChild(int index){this.componentList.get(index);}}package com.company.composite;public class Leaf extends Component {public Leaf(String name) {super(name);}@Overridepublic void op() {System.out.println(this.name);}}
抽象模式的demo
package com.company.composite;public abstract class Component {protected String name;public Component(String name) {this.name = name;}public void add(Component component){throw new UnsupportedOperationException();}public void remove(Component component){throw new UnsupportedOperationException();}public void getChild(int index){throw new UnsupportedOperationException();}}package com.company.composite;import java.util.ArrayList;import java.util.List;public class Composite extends Component {private List<Component> componentList;public Composite(String name) {super(name);this.componentList = new ArrayList<>();}@Overridepublic void op() {for(Component component : componentList){component.op();}}@Overridepublic void add(Component component){this.componentList.add(component);}@Overridepublic void remove(Component component){this.componentList.remove(component);}@Overridepublic void getChild(int index){this.componentList.get(index);}}package com.company.composite;public class Leaf extends Component {public Leaf(String name) {super(name);}@Overridepublic void op() {System.out.println(this.name);}}
