组合模式
组合模式(Composite),将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
当希望客户忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象时,就可以使用该模式。
结构图:
Component:组合中的对象声明接口,在适当情况下实现所有类公共接口的默认行为。声明一个接口用于访问和管理Component的子部件。
Leaf:在组合中表示叶子结点对象(没有子结点)。
Composite:定义有枝结点行为,用来存储子部件。
例:
public abstract class Component { protected String name; public Component(String name) { this.name = name; } public abstract void add(Component component); public abstract void remove(Component component); public abstract void show(); }
public class Leaf extends Component { public Leaf(String name) { super(name); } @Override public void add(Component component) { System.out.println("叶子结点没有分支,实现add只为消除与枝结点在抽象层次的区别"); } @Override public void remove(Component component) { System.out.println("叶子结点没有分支,实现remove只为消除与枝结点在抽象层次的区别"); } @Override public void show() { System.out.println(name); } }
public class Composite extends Component { private List<Component> list = new ArrayList<>(); public Composite(String name) { super(name); } @Override public void add(Component component) { list.add(component); } @Override public void remove(Component component) { list.remove(component); } public void show(){ for (Component component : list) { component.show(); } } }
public class Test { public static void main(String[] args) { Component root = new Composite("root"); // 根结点 Leaf leaf1 = new Leaf("叶子A1"); // 叶子结点A1 Leaf leaf2 = new Leaf("叶子A2"); // 叶子结点A2 Composite composite = new Composite("枝结点A3"); // 枝结点A3 composite.add(new Leaf("枝结点A3的叶子B1")); // 枝结点A3的叶子结点C1 composite.add(new Leaf("枝结点A3的叶子B2")); // 枝结点A3的叶子结点C2 root.add(leaf1); root.add(leaf2); root.add(composite); root.show(); root.remove(composite); // 移除枝结点A3 root.show(); } }