组合模式:
1. 将对象组合成树形结构以表示'部分-整体'的层次结构。
2. 组合模式使得用户对单个对象和组合对象的使用具有一致性。
/**
* 组合中的对象声明接口,在适当情况下,实现所有类共有接口的默认形为。
* 声明一个接口用于访问和管理Component的子部件。
*
*/
public abstract class Component {
private 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);
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/**
* 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关的操作。
*
*/
public class Composite extends Component{
private List<Component> childerns = new ArrayList<Component>();
public Composite(String name) {
super(name);
}
@Override
public void add(Component component) {
childerns.add(component);
}
/**
* 显示其枝节点名称,并对其下级进行遍历
*/
@Override
public void display(int depth) {
for(int i=0;i<depth;i++){
System.out.print("-");
}
System.out.println(this.getName());
// 遍历子节点
for(Component component:childerns){
component.display(depth+2);
}
}
@Override
public void remove(Component component) {
childerns.remove(component);
}
}
/**
* 叶节点对象:叶节点没有子结点
*
*/
public class Leaf extends Component{
public Leaf(String name) {
super(name);
}
@Override
public void add(Component component) {
System.out.println("cannot add to a leaf.");
}
@Override
public void display(int depth) {
for(int i=0;i<depth;i++){
System.out.print("-");
}
System.out.println(this.getName());
}
@Override
public void remove(Component component) {
System.out.println("cannot remove from a leaf.");
}
}
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// 生成树根,根上长出两叶
Composite root = new Composite("root");
root.add(new Leaf("leaf A"));
root.add(new Leaf("leaf B"));
// 根上再长出分枝Composite X,分枝上也长出两叶
Composite comp = new Composite("Composite X");
comp.add(new Leaf("leaf XA"));
comp.add(new Leaf("leaf XB"));
root.add(comp);
// Composite X分枝上再长出分枝Composite XY,分枝上也长出两叶
Composite comp2 = new Composite("Composite XY");
comp2.add(new Leaf("leaf XYA"));
comp2.add(new Leaf("leaf XYB"));
comp.add(comp2);
//根上又长出两叶
root.add(new Leaf("leaf C"));
Leaf leafD = new Leaf("leaf D");
root.add(leafD);
// D叶子被刮掉了
root.remove(leafD);
// 显示大树
root.display(1);
}
}