Composite定义:
将对象以树形结构组织起来,以达成“部分-整体” 的层次结构,使得客户端对单个对象和组合对象的使用具有一致性.
想到Composite就应该想到树形结构图。组合体内这些对象都有共同接口,当组合体一个对象的方法被调用执行 时,Composite将遍历(Iterator)整个树形结构,寻找同样包含这个方法的对象并实现调用执行。可以用牵一动百来形容。
Composite好处:
1.使客户端调用简单,客户端可以一致的使用组合结构或其中单个对象,用户就不必关系自己处理的是单个对象还是整个组合结构,这就简化了客户端代码。
2.更容易在组合体内加入对象部件. 客户端不必因为加入了新的对象部件而更改代码。
如何使用Composite?
首先定义一个接口或抽象类,这是设计模式通用方式了,其他设计模式对接口内部定义限制不多,Composite却有个规定,那就是要在接口内部定义一个用于访问和管理Composite组合体的对象们(或称部件Component).
举个例子,有一个盒子,里面放了一个球和别一个盒子,别一个盒子同样放一个球或又一个盒子,以此类推。。。
先定义一个接口:
//定义一个物体接口
public interface Substance {
//物体放进别一个物体
public void putin(Substance otherSubstance);
//物体移出别一个物体
public void getout(Substance otherSubstance);
//返回物体重量
public double weight();
}
//混合模式 一个物体是一个组合体,如盒子里放着别一个盒子
public class CompositeEquipment implements Substance{
// 定义一个Listr 用来存放'儿子'
private List equipment=new ArrayList();
public void putin(Substance otherSubstance){
this.equipment.add(otherSubstance);
}
public void getout(Substance otherSubstance){
this.equipment.remove(otherSubstance);
}
public double weight(){
double weight=0.0;
Iterator iter=equipment.iterator();
while(iter.hasNext())
weight+=((Substance)iter.next()).weight();
return weight;
}
}
//定义一个球,因为它是单独一个物体,是一个单独元素,称为叶子
public class Ball implements Substance{
//没有放进和移出别一物体方法,为空
public void putin(Substance otherSubstance){ }
public void getout(Substance otherSubstance){ }
public double weight(){
double weight=5.0;
return weight;
}
}
//盒子是一个组合体,有可能有别一个盒子在里面, 返回自身重量和里面东西的重量。
public class Case extends CompositeEquipment{
public double weight(){
double weight=1.0;
return weight+super.weight();
}
}
public class Test {
public static void main(String[] args){
Case bigCase=new Case();
Case smallCase=new Case();
bigCase.putin(smallCase);
bigCase.putin(new Ball());
smallCase.putin(new Ball());
System.out.println(bigCase.weight());
}
}
//output 12.00