左手邊ConcreteComponent是已經通過測試的程式碼, 為了降低耦合度, 對修改封閉, 對擴充開放, 擴充功能就以Decorator方式;
因此, 右手邊多了一層Decorator抽象類別, 同時原本繼承iComponent的operation()也被改宣告成virtual void operation,
繼續往下衍生類別ConcreteDecoratorA和ConcreteDecoratorB必須override void operation, 同時將擴充功能同時寫入
新增一個windows form application
同時加入一個新的類別檔案
1: public interface iComponent
2: {
3: void operation(); // 操作方法
4: }
5: public class ConcreteComponent : iComponent
6: {
7: public void operation()
8: {
9: MessageBox.Show("Check file format", "ConcreteComponent");
10: }
11: }
中間的抽象類別: Decorator , 其繼承iComponent且Decorator的子類別有ConcreteDecoratorA和 ConcreteDecoratorB
1: public abstract class Decorator : iComponent
2: {
3: private iComponent m_component;
4: // 預設建構子
5: public Decorator()
6: {
7: this.m_component = null;
8: }
9: // 傳參數建構子
10: public Decorator(iComponent component)
11: {
12: this.m_component = component;
13: }
14: public virtual void operation()
15: {
16: if (m_component != null)
17: {
18: m_component.operation();
19: }
20: }
21: }
擴充A: 值得注意的是傳入的icomponent實體, 初始化基礎類別(Decorator)的m_component
1: class ConcreteDecoratorA : Decorator
2: {
3: // 預設建構子
4: public ConcreteDecoratorA() { }
5: public ConcreteDecoratorA(iComponent icomponent) : base(icomponent)
6: {
7:
8: }
9: private string ProcessStatus { get; set; }
10: public override void operation()
11: {
12: base.operation();
13: ProcessStatus = "Sucessfully!";
14: MessageBox.Show("Process files " + ProcessStatus, "ConcreteDecoratorA");
15: }
16: }
擴充B
1: class ConcreteDecoratorB : Decorator
2: {
3: public ConcreteDecoratorB(iComponent icomponent) : base(icomponent)
4: {
5: }
6: public override void operation()
7: {
8: base.operation();
9: newFunction();
10: MessageBox.Show("File's content is correct!", "ConcreteDecoratorB");
11: }
12: void newFunction()
13: {
14: MessageBox.Show("New Function", "ConcreteDecoratorB");
15: }
16: }
-------------------------------------------------------------------------------------------------------------------------
1: private void button1_Click(object sender, EventArgs e)
2: {
3: ConcreteComponent CC = new ConcreteComponent();
4: CC.operation();
5: }
--------------------------------------------------------------------------------------------------------------
1: private void button2_Click(object sender, EventArgs e)
2: {
3: ConcreteComponent CC = new ConcreteComponent();
4: ConcreteDecoratorA CDA = new ConcreteDecoratorA(CC);
5: ConcreteDecoratorA CDB = new ConcreteDecoratorA(CC);
6: CDA.operation();
7: CDB.operation();
8: }
擴充A(原有功能)
擴充A(新的功能)
--------------------------------------------
擴充B(原有功能)
擴充B(新的功能)
參考資料: Visual C#程式設計實例演練與系統開發2013 許清榮
留言列表