Composite定義:
將對象以樹形結構組織起來
Composite比較容易理解
所以Composite模式使用到Iterator模式
Composite好處:
如何使用Composite?
首先定義一個接口或抽象類
下面的代碼是以抽象類定義
public abstract class Equipment
{
private String name;
//實價
public abstract double netPrice();
//折扣價格
public abstract double discountPrice();
//增加部件方法
public boolean add(Equipment equipment) { return false; }
//刪除部件方法
public boolean remove(Equipment equipment) { return false; }
//注意這裡
public Iterator iter() { return null; }
public Equipment(final String name) { this
}
抽象類Equipment就是Component定義
public class Disk extends Equipment
{
public Disk(String name) { super(name); }
//定義Disk實價為
public double netPrice() { return
//定義了disk折扣價格是
public double discountPrice() { return
}
Disk是組合體內的一個對象
還有一種可能是
abstract class CompositeEquipment extends Equipment
{
private int i=
//定義一個Vector 用來存放
private Lsit equipment=new ArrayList();
public CompositeEquipment(String name) { super(name); }
public boolean add(Equipment equipment) {
this
return true;
}
public double netPrice()
{
double netPrice=
Iterator iter=erator();
for(iter
netPrice+=((Equipment)iter
return netPrice;
}
public double discountPrice()
{
double discountPrice=
Iterator iter=erator();
for(iter
discountPrice+=((Equipment)iter
return discountPrice;
}
//注意這裡
//上面dIsk 之所以沒有
public Iterator iter()
{
return erator()
{
//重載Iterator方法
public boolean hasNext() { return i<equipment
//重載Iterator方法
public Object next()
{
if(hasNext())
return equipment
else
throw new NoSuchElementException();
}
}
上面CompositeEquipment繼承了Equipment
我們再看看CompositeEquipment的兩個具體類:盤盒Chassis和箱子Cabinet
public class Chassis extends CompositeEquipment
{
public Chassis(String name) { super(name); }
public double netPrice() { return
public double discountPrice() { return
}
public class Cabinet extends CompositeEquipment
{
public Cabinet(String name) { super(name); }
public double netPrice() { return
public double discountPrice() { return
}
至此我們完成了整個Composite模式的架構
我們可以看看客戶端調用Composote代碼:
Cabinet cabinet=new Cabinet(
Chassis chassis=new Chassis(
//將PC Chassis裝到Tower中 (將盤盒裝到箱子裡)
cabinet
//將一個
chassis
//調用 netPrice()方法;
System
System
上面調用的方法netPrice()或discountPrice()
Composite是個很巧妙體現智慧的模式
以論壇為例
Jive解剖
在Jive中 ForumThread是ForumMessages的容器container(組合體)
[thread]
|
|
|
|
|
我們在ForumThread看到如下代碼
public interface ForumThread {
public void addMessage(ForumMessage parentMessage
throws UnauthorizedException;
public void deleteMessage(ForumMessage message)
throws UnauthorizedException;
public Iterator messages();
}
類似CompositeEquipment
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27583.html