设计模式实践-命令模式

场景

向仪表发送采集命令

实现代码

仪表命令接口

namespace DesignPatterns.Command
{
    /// <summary>
    /// 仪表命令接口
    /// </summary>
    public interface IMeterCommand
    {
        /// <summary>
        /// 执行命令
        /// </summary>
        void Execute();
    }
}

采集命令

namespace DesignPatterns.Command
{
    /// <summary>
    /// 采集命令
    /// </summary>
    public class CollectCommand : IMeterCommand
    {
        /// <summary>
        /// 命令接受对象
        /// </summary>
        private readonly Receiver _receiver;

        /// <summary>
        /// Initializes a new instance of the <see cref="CollectCommand" /> class
        /// </summary>
        /// <param name="receiver">命令接受对象</param>
        public CollectCommand(Receiver receiver)
        {
            this._receiver = receiver;
        }

        /// <summary>
        /// 执行命令
        /// </summary>
        public void Execute()
        {
            this._receiver.Action("采集命令");
        }
    }
}

调用者对象

namespace DesignPatterns.Command
{
    /// <summary>
    /// 命令发送者
    /// </summary>
    public class Invoker
    {
        /// <summary>
        /// 命令对象
        /// </summary>
        private readonly IMeterCommand command;

        /// <summary>
        /// Initializes a new instance of the <see cref="Invoker" /> class
        /// </summary>
        /// <param name="command">命令对象</param>
        public Invoker(IMeterCommand command)
        {
            this.command = command;
        }

        /// <summary>
        /// 调用命令
        /// </summary>
        public void Call()
        {
            this.command.Execute();
        }
    }
}

接收者对象

namespace DesignPatterns.Command
{
    /// <summary>
    /// 命令发送者
    /// </summary>
    public class Invoker
    {
        /// <summary>
        /// 命令对象
        /// </summary>
        private readonly IMeterCommand command;

        /// <summary>
        /// Initializes a new instance of the <see cref="Invoker" /> class
        /// </summary>
        /// <param name="command">命令对象</param>
        public Invoker(IMeterCommand command)
        {
            this.command = command;
        }

        /// <summary>
        /// 调用命令
        /// </summary>
        public void Call()
        {
            this.command.Execute();
        }
    }
}

相关调用

Receiver receiver = new Receiver();
IMeterCommand command = new CollectCommand(receiver);
Invoker invoker = new Invoker(command);
invoker.Call();

Out

发送数据:采集命令
posted @ 2016-07-25 20:32  4Thing  阅读(108)  评论(0编辑  收藏  举报