我覺得裝飾圖案最令人困惑。請考慮「首先設計模式書」中提供的示例。裝飾圖案的替代品
因此,要獲得一個在DarkRoast雙摩卡和鞭子,你必須寫
Beverage beverage2 = new DarkRoast();
beverage2 = new Mocha(beverage2);
beverage2 = new Mocha(beverage2);
beverage2 = new Whip(beverage2);
我覺得這是不必要的。這裏是我的實現,
interface Beverage
{
int Cost();
}
class DarkRoast : Beverage
{
/* .... */
}
class Mocha : Beverage
{
/* .... */
}
class Whip : Beverage
{
/* .... */
}
// here is the changed part
class Order
{
List<Beverage> beverages = new List<Beverage> beverages();
public void AddItem(Beverage b)
{
beverages.Add(b);
}
public int Cost()
{
int cost;
foreach(Beverage b in beverages)
cost += b.Cost();
}
}
// use it like
Order order = new Order();
order.AddItem(new DarkRoast());
order.AddItem(new Mocha());
order.AddItem(new Mocha());
order.AddItem(new Whip());
int cost = order.Cost();
IMO,兩者都是相同的。如果是的話,這裏使用裝飾器模式的優點是什麼?
有什麼想法?
謝謝。這解釋得很好。 – 2009-08-08 18:37:57
你解釋得很好。 – 2010-09-28 20:44:28