组合模式
一、定义
将对象(objects)组合成树形结构来表示“部分-整体”层次结构,使得客户端一致地对待单个对象和组合对象。
二、类图表示
三、实现
1、Component
package pattern.structual.composite;
public abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public void display(int depth){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < depth; i++){
sb.append(" ");
}
System.out.println(String.format("%s--%s", sb, name));
}
@Override
public String toString() {
return String.format("Type: %s Name: %s", this.getClass().getSimpleName(), name);
}
public abstract void add(Component component);
public abstract void remove(Component component);
public abstract Component getChild(int index);
}
2、Leaf
package pattern.structual.composite;
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void add(Component component) {
System.out.println("can't add to a leaf");
}
@Override
public void remove(Component component) {
System.out.println("can't remove from a leaf");
}
@Override
public Component getChild(int index) {
System.out.println("can't get child from a leaf");
return null;
}
@Override
public void display(int depth) {
super.display(depth);
}
}
3、Composite
package pattern.structual.composite;
import java.util.ArrayList;
import java.util.List;
public class Composite extends Component {
private List<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 Component getChild(int index) {
return children.get(index);
}
@Override
public void display(int depth) {
super.display(depth);
for(Component com : children){
com.display(depth + 2);
}
}
}
四、使用
package pattern.structual.composite;
public class Client {
public static void main(String[] args) {
Component root = new Composite("Root");
root.add(new Leaf("Leaf A"));
root.add(new Leaf("Leaf B"));
Component composite = new Composite("Composite X");
composite.add(new Leaf("Leaf X1"));
composite.add(new Leaf("Leaf X2"));
root.add(composite);
root.add(new Leaf("Leaf C"));
root.display(0);
Component child = root.getChild(2);
System.out.println("Index-2: " + child);
root.remove(child);
root.display(0);
}
}
- 程序输出:
五、适用场合
- 想表示对象的“部分–整体”结构时
- 想在客户端一致的使用组合对象或单个对象