- 组合模式(Composite),将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
public abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public abstract void add(Component c);
public abstract void remote(Component c);
public abstract void display(int depth);
}
public class Composite extends Component {
private List<Component> children = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override public void add(Component c) {
children.add(c);
}
@Override public void remote(Component c) {
children.remove(c);
}
@Override public void display(int depth) {
for(int i=0;i<depth;i++){
System.out.print("-");
}
System.out.println(name);
for(Component c : children) {
c.display(depth + 2);
}
}
}
public class Leaf extends Component{
public Leaf(String name) {
super(name);
}
@Override public void add(Component c) {
System.out.println("cannot add to a leaf");
}
@Override public void remote(Component c) {
System.out.println("cannot remote from a leaf");
}
@Override public void display(int depth) {
for(int i=0;i<depth;i++){
System.out.print("-");
}
System.out.println(name);
}
}
public class ComponentMain {
public static void main(String[] args) {
final String s = new String();
final Composite root = new Composite("root");
root.add(new Leaf("leaf A"));
root.add(new Leaf("leaf B"));
final Composite comp = new Composite("Composite X");
comp.add(new Leaf("leaf XA"));
comp.add(new Leaf("leaf XB"));
root.add(comp);
final Composite comp2 = new Composite("Composite XY");
comp2.add(new Leaf("leaf XYA"));
comp2.add(new Leaf("leaf XYB"));
root.add(comp2);
root.add(new Leaf("leaf C"));
final Leaf leaf = new Leaf("leaf D");
root.add(leaf);
root.remote(leaf);
root.display(1);
}
}