设计模式之命令模式

命令模式:是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。

主要意图:将一个请求封装成一个对象,从而使您可以用不同的请求对客户进行参数化。

主要解决:在软件系统中,行为请求者与行为实现者通常是一种紧耦合的关系,但某些场合,比如需要对行为进行记录、撤销或重做、事务等处理时,这种无法抵御变化的紧耦合的设计就不太合适。

解决方案:通过调用者调用接受者执行命令,顺序:调用者→接受者→命令。

优点:1、降低了系统耦合度。

2、新的命令可以很容易添加到系统中去。

缺点:

使用命令模式可能会导致某些系统有过多的具体命令类。

命令模式类图:

代码实现:

客户端代码:

using System;

namespace _04命令模式_基础版
{
    class Program
    {
        static void Main(string[] args)
        {
            Receiver r = new Receiver();
            Command c = new ConcreteCommand(r);
            Invoker i = new Invoker();
            i.SetCommand(c);
            i.ExecuteCommand();

            Console.Read();
        }
    }
}

调用者:

using System;
using System.Collections.Generic;
using System.Text;

namespace _04命令模式_基础版
{
    class Invoker
    {
        private Command command;
        public void SetCommand(Command command)
        {
            this.command = command;
        }
        public void ExecuteCommand()
        {
            command.Execute();
        }
    }
}

抽象命令对象:

using System;
using System.Collections.Generic;
using System.Text;

namespace _04命令模式_基础版
{
    abstract class Command
    {
        protected Receiver receiver;
        public Command(Receiver receiver)
        {
            this.receiver = receiver;
        }
        abstract public void Execute();
    }
}

具体的命令对象:

using System;
using System.Collections.Generic;
using System.Text;

namespace _04命令模式_基础版
{
    class ConcreteCommand:Command
    {
        public ConcreteCommand(Receiver receiver):base(receiver)
        { }
        public override void Execute()
        {
            receiver.Action();
        }
    }
}

接收者:

using System;
using System.Collections.Generic;
using System.Text;

namespace _04命令模式_基础版
{
    class Receiver
    {
        public void Action()
        {
            Console.WriteLine("执行请求!");
        }
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李金轩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值