现在的位置: 首页 > 综合 > 正文

组合模式

2013年01月19日 ⁄ 综合 ⁄ 共 1646字 ⁄ 字号 评论关闭
组合模式
1.定义
    组合对象用树型结构层次来表示部分整体的关系。组合对象使单个的对象及整体对象的使用具有一致性。
    compose objects into tree structures to represent part-whole
hierarchies. Composite lets clients treat individual objects and
compositions uniformly.
2.个人理解
    在《数据结构》的树型结构中,经常要用到节点及树枝,但它们是被客户同样对待的。一个节点往往包含("has-a" relationship)相同类型的数组。
3.结构图
    
4.实现
    /**
 * this source is from <design pattern> chinese edition on P112.
 */
package composite;
import java.util.*;
abstract class Equipment{
private String name;
private double price;
protected List<Equipment> equipments;
protected Equipment(String name){
this.name=name;
}
abstract double Price();
void add(Equipment e){
this.equipments.add(e);
}
void delete(Equipment e){
this.equipments.remove(e);
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
class CompositeEquipment extends Equipment{
public CompositeEquipment(String name){
super(name);
this.equipments=new ArrayList<Equipment>();
}
public double Price(){
double total=0;
for(Equipment equip:equipments){
total+=equip.Price();
}
return total;
}
}
class Chassis extends CompositeEquipment{
public Chassis(String name){
super(name);
}
}
class Bus extends Equipment {
public Bus(String name,double price){
super(name);
this.setPrice(price);
}
public double Price(){
return this.getPrice();
}
}
class FloppyDisk extends Equipment {
public FloppyDisk(String name,double price){
super(name);
this.setPrice(price);
}
public double Price(){
return this.getPrice();
}
}
public class Composite {
/**
* @param args
*/
public static void main(String[] args) {
Chassis chassis=new Chassis("Pc chassis");
chassis.add(new Bus("Pc Bus",23.5));
chassis.add(new FloppyDisk("Pc FloppyDisk",13.5));
System.out.println(chassis.Price());
}
}
参考:
1.http://en.wikipedia.org/wiki/Composite_pattern

抱歉!评论已关闭.