一、介绍
组合模式(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 display(int depth); } import java.util.ArrayList; public class Composite extends Component { private ArrayList<Component> children = new ArrayList<>(); public Composite(String name) { super(name); } @Override public void add(Component component) { children.add(component); } @Override public void remove(Component component) { children.remove(component); } @Override public void display(int depth){ for (int i = 0; i < depth; i++) { System.out.print("-"); } System.out.println(name); for (Component child : children) { child.display(depth+2); } } ; } 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 display(int depth) { } }
测试
public class Client { public static void main(String[] args) { Composite root=new Composite("root"); root.add(new Leaf("Leaf A")); root.add(new Leaf("Leaf B")); Composite comp=new Composite("Composit x"); comp.add(new Leaf("Leaf XA")); comp.add(new Leaf("Leaf XB")); root.add(comp); Composite comp2=new Composite("Composit xy"); comp2.add(new Leaf("Leaf XyA")); comp2.add(new Leaf("Leaf XyB")); comp.add(comp2); root.display(1); } }