Composite 设计模式
定义
将对象组成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有唯一性。
结构

示例
Component:组件中的对象声明接口。在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理 Component 的子组件。
abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public abstract void add(Component c);
public abstract void remove(Component c);
public abstract void display(int depth);
}
Leaf:表示叶子节点对象。叶子节点没有子节点。
class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void add(Component c) {
System.out.println("Can not add to a leaf");
}
@Override
public void remove(Component c) {
System.out.println("Can not remove from a leaf");
}
@Override
public void display() {
// print super.name
}
}
This chapter requires login to view full content. You are viewing a preview.
Login to View Full Content