组合模式
组合模式特别适合处理那种整体和部分抽象为统一体的问题,比如目录接口(java中的File类即可以表示路径,也可以表示文件),树状接口(树枝和树叶)
组合模式的核心在于部分和整体的抽象为同一物体,至于抽象之后有什么需求再加相应的方法,下边是一个有遍历需求的组合模式定义,因为需要组合成一棵树和遍历,所以需要在接口添加getChildren和addChild方法,组合模式考虑给接口添加什么方法的时候最好从客户端的使用来考虑会简单一些
类图:
抽象接口:
public interface Component {
public void print();
public List<Component> getChildren();
public void addChild(Component child);
}
叶子:
public class Leaf implements Component {
private String name;
public Leaf(String name) {
this.name = name;
}
@Override
public void print() {
System.out.println(name);
}
@Override
public List<Component> getChildren() {//叶子节点无子节点,直接返回长度为0的容器即可
return new ArrayList<Component>();
}
@Override
public void addChild(Component child) {//叶子节点不支持添加子节点
throw new RuntimeException("不支持操作");
}
}
树枝节点:
public class Composite implements Component {
private String name;
private List<Component> children;
public Composite(String name) {
this.name = name;
children = new ArrayList<Component>();
}
@Override
public void print() {
System.out.println(name);
}
public List<Component> getChildren() {
return children;
}
@Override
public void addChild(Component child) {
children.add(child);
}
}
客户端:因为要遍历,所以需要getChildren方法,因为要组合成一棵树,所以需要addChild方法
public class Client {
public static void main(String[] args) {
// 定义一颗树
Component root = new Composite("根");
Component branch11 = new Composite("第一级树枝1");
Composite branch12 = new Composite("第一级树枝2");
root.addChild(branch11);
root.addChild(branch12);
Component branch211 = new Leaf("树叶1");
Component branch212 = new Leaf("树叶2");
branch12.addChild(branch211);
branch12.addChild(branch212);
iterateTree(root);
}
private static void iterateTree(Component component) {
component.print();
List<Component> children = component.getChildren();
for (Component child : children) {
iterateTree(child);
}
}
}
输出:
根
第一级树枝1
第一级树枝2
树叶1
树叶2