模式定义
在实际的编程中常常出现这样的情形:A对象包含了另外一个对象B,而B又包含了其他对象C和D,好比一棵树,树枝上有树枝,树枝上再有小树枝或树叶,这样的层次结构可以用Composite模式来实现。因此Composite模式将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。
使用范围
- 多个对象之间存在层次组合的结构
- 使组合对象或者单个对象对于客户而言具有访问的一致性
使用方法
将组合对象与单个对象的共有属性或方法剥离出一个抽象类,组合对象与单个对象分别继承该抽象类并实例化。
举例说明
我们用Composite来描述一棵树。树是树枝和树叶的抽象,树有名字(可能为树枝,也可能为树叶,体现为具体的子类),用add方法表示树枝可以有其他树枝或树叶,用printAll表述列举一棵树的完整结构。
import java.util.ArrayList;
public abstract class Tree {
protected ArrayList list = new ArrayList();
protected String name = null;
public Tree(){};
public abstract void add(Tree t);
public abstract void remove(Tree t);
public abstract void printAll();
}
树枝节点:
public class Branch extends Tree {
public Branch(String name){
this.name = name;
}
public void add(Tree t) {
list.add(t);
}
public void printAll() {
for (int i=0; i< list.size(); i++){
System.out.println(name);
System.out.println("|---");
((Tree)list.get(i)).printAll();
}
}
public void remove(Tree t) {
if (list.contains(t))
list.remove(t);
}
}
树叶节点,注意树叶属于最低级的一个树,不再包含其他树的实例对象,因此不存在add方法。
public class Leaf extends Tree {
public Leaf(String name){
this.name = name;
}
public void add(Tree t) {
return;
}
public void printAll() {
System.out.println(name);
}
public void remove(Tree t) {
return;
}
}
最后,给出一棵树的完整结构,比如:
通过Tree.add方法在树枝上加树枝或加叶,即能实现一棵完整的树。
public class Client {
public static void main(String args[]){
Tree root= new Branch("Root");
Tree branch1 = new Branch("B1");
Tree branch2 = new Branch("B2");
Tree branch3 = new Branch("B3");
Tree branch4 = new Branch("B4");
Tree leaf1 = new Leaf("L1");
Tree leaf2 = new Leaf("L2");
Tree leaf3 = new Leaf("L3");
root.add(branch1);
root.add(branch3);
branch1.add(branch2);
branch1.add(leaf1);
branch2.add(branch4);
branch2.add(leaf2);
branch3.add(leaf3);
root.printAll();
}
}
类结构示意
该样例的类结构如下:
下载示例
本文介绍复合模式(Composite Pattern),一种用于处理层次结构的对象组合模式。它允许客户端一致地处理单个对象和组合对象,通过示例代码展示如何创建树形结构,并提供了一致性的访问方式。
1817

被折叠的 条评论
为什么被折叠?



