组合模式:Composite Pattern,又叫作整体-部分(Part-Whole)模式,它的宗旨是通过将单个对象(叶子节点)和组合对象(树枝节点)用相同的接口进行表示,使得客户对单个对象和组合对象的使用具有一致性,属于结构型设计模式
组合模式一般用于描述整体和部分的关系,将对象组织到树形结构中
- 顶层的节点被称为根节点
- 根节点下面可以包含树枝节点和叶子节点
- 树节点下面又可以包含树枝节点和叶子节点
在组合模式中,整个树形结构中的对象都属于同一种类型,带来的好处就是用户不需要辨别是树枝节点还是叶子节点,可以直接进行操作,给用户的使用带来极大的便利
组合模式的一般用途:
- 希望客户端可以忽略组合对象和单个对象的差异
- 对象层次具备整体和部分,呈树形结构
UML 图:
通用写法:
public class CompositeDemo {public static void main(String[] args) {// 创建根结点Component root = new Composite("root");// 创建一个树枝节点Component branchA = new Composite("---branchA");Component branchB = new Composite("------branchB");// 创建叶子节点Component leafA = new Leaf("------leafA");Component leafB = new Leaf("---------leafB");Component leafC = new Leaf("---leafC");// 节点组装root.addChild(branchA);root.addChild(leafC);branchA.addChild(leafA);branchA.addChild(branchB);branchB.addChild(leafB);String result = root.operation();System.out.println(result);}// 抽象节点static abstract class Component {protected String name;public Component(String name) {this.name = name;}public abstract String operation();public boolean addChild(Component component) {throw new UnsupportedOperationException("addChild not supported");}public boolean removeChild(Component component) {// 直接抛异常而非抽象方法的原因:// 使用了抽象方法,则子类必须实现,这样就体现不了各类子类的差异// 而使用抛异常,则子类无需实现与本身功能无关的方法throw new UnsupportedOperationException("removeChild not supported");}public Component getChild(int index) {throw new UnsupportedOperationException("getChild not supported");}}// 树枝节点static class Composite extends Component {private List<Component> components;public Composite(String name) {super(name);this.components = new ArrayList<>();}@Overridepublic String operation() {StringBuilder builder = new StringBuilder(this.name);for (Component component : this.components) {builder.append("\n");builder.append(component.operation());}return builder.toString();}@Overridepublic boolean addChild(Component component) {return components.add(component);}@Overridepublic boolean removeChild(Component component) {return components.remove(component);}@Overridepublic Component getChild(int index) {return components.get(index);}}// 叶子节点static class Leaf extends Component {public Leaf(String name) {super(name);}@Overridepublic String operation() {return this.name;}}}
