组合模式解决的问题是:每次用户可能使用不同的个体组合方式,而这些组合方式的个数可能是很大量级的,这时我们无法在程序中枚举每一种组合形式,然后对这种组合执行自己的操作。
采用组合问题将无需枚举每种组合形式。
组合模式的UML:
涉及的各个元素:
1.Component 是组合中的对象声明接口,在适当的情况下,实现所有类工人有接口的默认行为。声明一个接口用于访问和管理Component子部件。
2.Leaf 在组合中表示叶子结点对象,叶子结点没有子结点。
3.Composite 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和 删除(remove)等。
以下情况下适用Composite模式:
1.你想表示对象的部分-整体层次结构
2.你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。
下面是组合模式的一个实现:
import java.util.*;
//组合接口类
interface Composite{
public void echo();
}
//叶子类
class Leaf implements Component{
String str;
public Leaf (String str){
this.str=str;
}
public void echo(){
System.out.println(str);
}
}
//组合类(组合类至少包括两个基本成员方法)
class Composite implements Component{
List<Composite> cList=new ArrayList<Composite> ();
public void add(Composite c){
cList.add(c);
}
public void echo(){
Iterator<Composite> it=cList.iterator();
while(it.hasNext()){
Component tmp=it.next();
tmp.echo();
}
}
}
//测试类
public class TestComposite{
public static void main(String[] args){
Leaf l1=new Leaf("leaf1");
Leaf l2=new Leaf("leaf2");
Leaf l3=new Leaf("leaf3");
Composite cp1=new Composite();
Composite cp2=new Composite();
cp1.add(l1);
cp1.add(l2);
cp2.add(cp1);
cp2.add(l3);
cp2.echo();
}
}