组合模式,将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。
角色:
1. Component 是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component子部件
2. Leaf 在组合中表示叶子结点对象,叶子结点没有子结点
3. Composite 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除(remove)等
代码如下:
Componnent类
package src2;
public class Component {
protected String name;
public Component(String name) {
super();
this.name = name;
}
public void Add(Component c) {
}
public void Remove(Component c) {
}
public void Display(int depth){
}
}
Leaf类
package src2;
public class Leaf extends Component{
public Leaf(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public void Add(Component c) {
System.out.println("没有此功能");
}
public void Remove(Component c){
System.out.println("没有此功能");
}
public void Display(int depth) {
System.out.println("-"+depth + name);
}
}
Composite类
package src2;
import java.util.*;
public class Composite extends Component{
private List<Component> list = new ArrayList<Component>();
public Composite(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public void Add(Component c) {
list.add(c);
}
public void Remove(Component c){
list.remove(c);
}
public void Display(int depth){
System.out.println("-" + depth + name);
for (Component item : list) {
item.Display(depth + 2);
}
}
}
客户端代码
package src2;
public class t1 {
public static void main(String[] args) {
Composite root = new Composite("root");
root.Add(new Leaf("Leaf A"));
root.Add(new Leaf("Leaf B"));
Composite comppComposite = new Composite("compX");
comppComposite.Add(new Leaf("Leaf XA"));
comppComposite.Add(new Leaf("Leaf XB"));
root.Add(comppComposite);
Composite comp2 = new Composite("compY");
comp2.Add(new Leaf("Leaf XYA"));
comp2.Add(new Leaf("Leaf XYB"));
comppComposite.Add(comp2);
root.Add(new Leaf("Leaf C"));
Leaf leaf = new Leaf("Leaf D");
root.Add(leaf);
root.Remove(leaf);
root.Display(1);
}
}