淺讀《大話設計模式》————6、穿什么有這么重要?——裝飾模式
淺讀《大話設計模式》————6、穿什么有這么重要?——裝飾模式
如果不是看到有這么好的一個設計模式,我想我能給的設計也就是小菜扮靚第一版。不會采用第二版的原因是我覺得這樣只會更冗余更復雜。如果說穿衣服本身就是人這個對象應該具有的基本屬性,那么看起來似乎這種設計也是合理的。關鍵是人有很多很多穿法,這樣無休止下去,維護也是大問題。看來打扮不能簡單的做為一種操作,能視為基本操作的只有打扮好了以后展示。如同吃飯可以吃很多不同的東西,吃什么不是基本屬性,而只有消化食物才是。理解起來還是比較簡單的:無論穿什么,穿好了,就統稱服裝,所以是服裝展示;無論吃什么,吃進去了就是食物,所以就只剩下消化食物了。
裝飾模式:動態地給一個對象添加一些額外的職責,就增加功能來說,裝飾模式比生成子類更為靈活[DP]。
我很佩服裝飾模式的設計,基本的代碼結構無疑讓人眼前一亮:
1、Component類
abstract class Component
{
Public abstract void Operation();
}
2、ConcreteComponent類
Classs ConcreteComponent : Component
{
Public override void Operation()
{
Console.WriteLine("具體對象的操作");
}
}
3、Decorator類
Abstract class Decorator:Component
{
Protected Component component;
Public void SetComponent(Component component)
{
This.component = component ;
}
Public override void Operation()
{
If( component != null)
{
Component .Operation();
}
}
}
4、ConcreteDecoratorA 類
Class ConcreteDecoratorA : Decorator
{
Private string addedState; //本類獨有功能,以區別于ConcreteDecoratorB
Public override void Operation()
{
base.Operation();
addedState = "New State";
Console.WriteLine("具體裝飾對象A的操作");
}
}
Class ConcreteDecoratorB : Decorator
{
Public override void Operation()
{
Base.Operation();
AddedBehavior();
Console.WriteLine("具體裝飾對象B的操作");
}
Private void AddedBehavior() //本類獨有的方法,以區別于A類
{}
}
5、客戶端代碼
Static void Main(string [] args)
{
ConcreteComponent c = new ConcreteCompenent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();
D1.SetComponent(c);
D2.SetComponent(d1);
D2.operation();
Console.Read();
}
這里用到了面向對象的繼承的特性,所以在建立一個對象后,可以完全獨立的一步一步的進行裝飾,就像一件一件穿衣服似的。難道這樣的設計不讓人驚嘆嗎?還有關鍵的是:“如果只有一個ConcreteComponent類而沒有抽象的Component類,那么Decorator類可以是ConcreteComponent的一個子類。同樣道理,如果只有一個ConcreteDecorator類,那么就沒有必要建立一個單獨的Decorator類,而可以把Decorator和ConcreteDecorator的責任合并成一個類。”
裝飾模式總結:裝飾模式是為了為已有功能動態的添加更多功能的一種方式。
他把每個要裝飾的功能放在單獨的類中,并讓每個類包裝他所要裝飾的對象,因此,當需要執行特定行為時,客戶代碼就可以在運行時根據需要有選擇地、按順序地使用裝飾功能包裝對象了[DP]。
裝飾模式很靈活,靈活到裝飾本身并沒有限制順序,大部分時候,超人那種內褲穿在外面的打扮好像不太合時宜,所以要注意裝飾的順序哦~
posted on 2009-04-16 20:55 Tim 閱讀(406) 評論(0) 編輯 收藏 引用 所屬分類: 設計模式