設計模式學習筆記十五——Command模式

來源:互聯網
上載者:User
動機:將一組行為抽象為對象,實現行為要求者和行為實現者之間的解耦,並且支援對行為進行記錄、撤銷、重做、事務等處理。

情境:考慮一系列文檔操作:開啟、複製、剪下、粘帖。

結構

代碼實現
/**//*
 * 行為實現者
*/
namespace DesignPattern.Command
{
    public class Application
    {
        public void OpenDocument()
        {
        }
    }
}

/**//*
 * 行為實現者
*/
namespace DesignPattern.Command
{
    public class Document
    {
        string path;
        public Document(string docPath)
        {
            path = docPath;
        }

        public void Copy()
        {
        }

        public void Cut()
        {
        }

        public void Paste()
        {
        }
    }
}

/**//*
 * 行為對象
*/
namespace DesignPattern.Command
{
    // 定義行為介面
    public interface ICommand
    {
        void Execute();
    }

    // 開啟文檔
    public class OpenCommand : ICommand
    {
        // 使用應用程式開啟文檔
        Application app;

        public OpenCommand(Application application)
        {
            app = application;
        }

        public void Execute()
        {
            app.OpenDocument();
        }
    }

    public class CopyCommand : ICommand
    {
        Document doc;

        public CopyCommand(Document document)
        {
            doc = document;
        }

        public void Execute()
        {
            doc.Copy();
        }
    }

    public class CutCommand : ICommand
    {
        Document doc;

        public CutCommand(Document document)
        {
            doc = document;
        }

        public void Execute()
        {
            doc.Cut();
        }
    }

    public class PasteCommand : ICommand
    {
        Document doc;

        public PasteCommand(Document document)
        {
            doc = document;
        }

        public void Execute()
        {
            doc.Paste();
        }
    }
}

/**//*
 * 行為要求者
*/
namespace DesignPattern.Command
{
    public class Client
    {
        public void DealDocument()
        {
            Document doc = new Document("DocumentPath");
            Command command = new CopyCommand(doc);
            command .Execute();
        }
    }
}

要點
      1、本模式的基本目的在於將行為要求者和實現者解耦,常見的實現方法是將行為抽象為對象。
      2、實現行為的具體對象有時候根據需要可能會儲存一些額外的狀態資訊,比如實現撤銷、重做時。
      3、可以和Composite模式結合,實現多個命令的組合成複雜命令。
      4、本模式和Delegate有些類似。但兩者定義行為介面的規範有所區別:本模式以物件導向中“介面-實現”來定義行為介面規範,更嚴格,更符合抽象原語;Delegate以函數簽名來定義行為介面規範,更靈活,但抽象能力比較弱。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.