结构型模式3:
合成模式:合成模式将对象组织到树结构中,可以用来描述整体与部分的关系。合成模式就是一个处理对象的树结构的模式。合成模式把部分与整体的关系用树结构表示出来。合成模式使得客户端把一个个单独的成分对象和由他们复合而成的合成对象同等看待。
追MM比喻:COMPOSITE―Mary今天过生日。“我过生日,你要送我一件礼物。”“嗯,好吧,去商店,你自己挑。”“这件T恤挺漂亮,买,这条裙子好看,买,这个包也不错,买。”“喂,买了三件了呀,我只答应送一件礼物的哦。”“什么呀,T恤加裙子加包包,正好配成一套呀,小姐,麻烦你包起来。”“……”,MM都会用Composite模式了,你会了没有?
将“客户代码与复杂的对象容器结构”解耦是Composite模式的核心思想。解耦之后,客户代码将与纯粹的抽象接口(而非对象容器复杂内部实现结构)发生依赖关系,从而更能“应对变化”。
首先定义一个接口或抽象类Component:
package composite;import java.util.Iterator;public abstract class Equipment{ //名称 private String name; //价格 public abstract double netPrice(); //增加一个部件 public boolean add(Equipment equ){ return false; } //删除一个部件 public boolean remove(Equipment equ){ return false; } //迭代指针 public Iterator iter(){ return null; } //构造方法 public Equipment(String name){ this.name=name; }}
Disk类Leaf角色:
package composite;public class Disk extends Equipment{ //构造方法 public Disk(String name){ super(name); } //定价 public double netPrice(){ return 1.2; }}
CompositeEquipment 类Composite角色:
package composite;import java.util.*;public abstract class CompositeEquipment extends Equipment{ private List equipment=new ArrayList(); public CompositeEquipment(String name){ super(name); } public boolean add(Equipment equ){ equipment.add(equ); return true; } public boolean remove(Equipment equ){ equipment.remove(equ); return true; } public Iterator iter(){ return equipment.iterator(); } public double netPrice(){ double netprice=0; Iterator it=equipment.iterator(); while(it.hasNext()){ netprice+=((Equipment)it.next()).netPrice(); } return netprice; } }CompositeEquipment的两个具体类:
package composite;public class Chassis extends CompositeEquipment{ public Chassis(String name){ super(name); } public double netPrice(){ return 3.0+super.netPrice(); }}
package composite;public class Cabinet extends CompositeEquipment{ public Cabinet(String name){ super(name); } public double netPrice(){ return 3.0+super.netPrice(); } }
运行类:
package composite;public class Composite{ public static void main(String[] args){ Cabinet cabinet=new Cabinet("Tomer"); Chassis chassis=new Chassis("PC chassis"); cabinet.add(chassis); chassis.add(new Disk("120Gb")); System.out.println(cabinet.netPrice()); }}
输出:7.2 Press any key to continue...
Composite好处:
1.使客户端调用简单,客户端可以一致的使用组合结构或其中单个对象,用户就不必关系自己处理的是单个对象还是整个组合结构,这就简化了客户端代码。
2.更容易在组合体内加入对象部件. 客户端不必因为加入了新的对象部件而更改代码。如何使用?
首先定义一个接口或抽象类,这是设计模式通用方式了,其他设计模式对接口内部定义限制不多,Composite却有个规定,那就是要在接口内部定义一个用于访问和管理Composite组合体的对象们(或称部件Component).