( Design Patterns ) Structural Design Patterns 1 -- Decorator pattern

Definition

Attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Components

  1. ComponentBase: base class for all concrete components and decorators.
  2. ConcreteComponent: inherits from ComponentBase. Concrete component classes that may be wrapped by the decorators.
  3. DecoratorBase: base class for decorators. It has a constructor that accepts a ComponentsBase as its parameters.
  4. ConcreteDecorator: It may include some additional methods which extend the functionality of components.
Decorator pattern uml
Decorator pattern uml

Sample code

static class Program
{
    static void Main()
    {
        var component = new ConcreteComponent();
        var decorator = new ConcreteDecorator(component);
        decorator.Operation();
    }
}

public abstract class ComponentBase
{
    public abstract void Operation();
}

class ConcreteComponent : ComponentBase
{
    public override void Operation()
    {
        Console.WriteLine("ConcreteComponent.Operation()");
    }
}

public abstract class DecoratorBase : ComponentBase
{
    private readonly ComponentBase _component;

    protected DecoratorBase(ComponentBase component)
    {
        _component = component;
    }

    public override void Operation()
    {
        _component.Operation();
    }
}

public class ConcreteDecorator : DecoratorBase
{
    public ConcreteDecorator(ComponentBase component) : base(component) { }

    public override void Operation()
    {
        base.Operation();
        Console.WriteLine("[ADDITIONAL CODE BLOCK]");
    }
}

Advantages

  1. It helps to achieve extending the components' functionality by avoiding changing components' original logic.
  2. It provides a flexible alternative to subclassing for extending functionality, which could change components' behavior at runtime.

Reference

Design Patterns 2 of 3 - Structural Design Patterns - CodeProject
Head First Design Patterns - O'Reilly Media

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1 場景問題# 1.1 復(fù)雜的獎金計算## 考慮這樣一個實際應(yīng)用:就是如何實現(xiàn)靈活的獎金計算。 獎金計算是相對復(fù)雜...
    七寸知架構(gòu)閱讀 4,293評論 4 67
  • 定義 裝飾器模式又名包裝(Wrapper)模式。裝飾器模式以對客戶端透明的方式拓展對象的功能,是繼承關(guān)系的一種替代...
    步積閱讀 36,546評論 0 38
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • 設(shè)計模式匯總 一、基礎(chǔ)知識 1. 設(shè)計模式概述 定義:設(shè)計模式(Design Pattern)是一套被反復(fù)使用、多...
    MinoyJet閱讀 4,073評論 1 15
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,624評論 18 399

友情鏈接更多精彩內(nèi)容