設(shè)計模式- 裝飾器模式(Decorator Pattern)

定義

裝飾器模式(Decorator Pattern):動態(tài)地給一個對象添加一些額外的職責(zé)。就增加功能來說,裝飾器模式相比生成子類更為靈活

允許向一個現(xiàn)有的對象添加新的功能,同時又不改變其結(jié)構(gòu)。這種類型的設(shè)計模式屬于結(jié)構(gòu)型模式,它是作為現(xiàn)有的類的一個包裝。
這種模式創(chuàng)建了一個裝飾類,用來包裝原有的類,并在保持類方法簽名完整性的前提下,提供了額外的功能。

C#例子

    public interface ICommand
    {
        void Executed();
    }

    public class CreateOrder : ICommand
    {
        public void Executed()
        {
            Console.WriteLine("創(chuàng)建了訂單信息!");
        }
    }

    public class WriteLogDecorator : ICommand
    {
        private ICommand _command;
        public WriteLogDecorator(ICommand command) {
            _command = command;
        }
        public void Executed()
        {
            Console.WriteLine("記錄了日志!");
            _command.Executed();
        }
    }

    public class PayDecorator : ICommand
    {
        private ICommand _command;
        public PayDecorator(ICommand command)
        {
            _command = command;
        }
        public void Executed()
        {
            _command.Executed();
            Console.WriteLine("支付了完成了!");
        }
    }
    public class StockDecorator : ICommand
    {
        private ICommand _command;
        public StockDecorator(ICommand command)
        {
            _command = command;
        }
        public void Executed()
        {
            _command.Executed();
            Console.WriteLine("扣減了庫存!");
        }
    }

        static void Main(string[] args)
        {
            // 記錄日志、創(chuàng)建單據(jù)
            var cmd1 = new WriteLogDecorator(new CreateOrder());
            cmd1.Executed();
            // 記錄日志、創(chuàng)建單據(jù)、扣減庫存、支付
            var cmd2 = new WriteLogDecorator(new StockDecorator(new PayDecorator(new CreateOrder())));
            cmd2.Executed();
            Console.ReadLine();
        }

裝飾器模式適用情形:

  • 在不想增加很多子類的情況下擴(kuò)展一個類的功能
  • 動態(tài)增加功能,動態(tài)撤銷

裝飾器模式特點:

  • 可代替繼承
  • 裝飾類和被裝飾類可以獨立發(fā)展,不會相互耦合,裝飾模式是繼承的一個替代模式,裝飾模式可以動態(tài)擴(kuò)展一個實現(xiàn)類的功能
  • 多層裝飾比較復(fù)雜
  • 都必須繼承ICommand

其他

源碼地址

dotnet-design-patterns

其他設(shè)計模式

23種設(shè)計模式

?著作權(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)容

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