設計模式之裝飾模式 裝飾模式 Decorator

裝飾模式 Decorator

Intro

裝飾模式,動態地給一個對象添加一些額外的職責,就增加功能來說,裝飾模式比生成子類更爲靈活

使用場景

裝飾模式是爲已有功能動態地添加更多功能的一種方式

當系統需要新功能的時候,是向舊的類中添加新的代碼,這些新加的代碼通常裝飾了原有類的核心職責或主要行爲,但是往往會在主類中加入新的字段/方法/邏輯,從而增加了主類的複雜度,
而這些新加入的東西僅僅是爲了滿足一些只在某種特定情況下才會執行的特殊行爲的需要

裝飾模式提供了一個很好的方案,它把每個要裝飾的功能放在單獨的類中,並讓這個類包裝它要裝飾的對象,
當需要執行特殊行爲時,就可以在運行時根據需要有選擇地、按順序地使用裝飾功能包裝對象了。

裝飾模式的優點時把類中的裝飾功能從類中搬移去除,這樣可以簡化原有的類,這樣做就有效地把類的核心職責和裝飾功能區分開了,而且可以去除相關類中重複的裝飾邏輯。

Prototype

  • Component 定義一個對象的抽象,可以給這些對象動態的添加職責
  • ConcreteComponent 定義一個具體的對象,也可以給這個對象添加一些職責
  • Decorator 裝飾抽象類,繼承了 Component,從外類來擴展 Component 類的功能,但對於 Component 來說是無需知道 Decorator 的存在的
  • ConcreteDecorator 具體的裝飾對象,起到給 Component 添加職責的功能
internal abstract class Component
{
    public abstract void Operation();
}
internal class ConcreteComponent : Component
{
    public override void Operation()
    {
        Console.WriteLine("Operation executed in ConcreteComponent");
    }
}

internal abstract class Decorator : Component
{
    protected Component Component;

    public void SetComponent(Component component)
    {
        Component = component;
    }

    public override void Operation()
    {
        Component?.Operation();
    }
}
internal class DecoratorA : Decorator
{
    private string _state;

    public override void Operation()
    {
        base.Operation();
        _state = "executed";
        Console.WriteLine($"operation in DecoratorA, state:{_state}");
    }
}
internal class DecoratorB : Decorator
{
    public override void Operation()
    {
        base.Operation();
        Console.WriteLine("operation in DecoratorB");
        AddBehavior();
    }

    private void AddBehavior()
    {
        Console.WriteLine("another behavior");
    }
}


Component component = new ConcreteComponent();
Decorator decorator = new DecoratorA();
decorator.SetComponent(component);
decorator.Operation();

Decorator decorator1 = new DecoratorB();
decorator1.SetComponent(decorator);
decorator1.Operation();

More

裝飾器模式主要解決繼承關係過於複雜的問題,通過組合來替代繼承。它主要的作用是給原始類添加增強功能。這也是判斷是否該用裝飾器模式的一個重要的依據。

Reference

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章