设计模式实践-命令模式

场景

向仪表发送采集命令

实现代码

仪表命令接口

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

发送数据:采集命令

转载于:https://www.cnblogs.com/4thing/p/5705227.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值