命令模式:是一种数据驱动的设计模式,它属于行为型模式。请求以命令的形式包裹在对象中,并传给调用对象。调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令。
主要意图:将一个请求封装成一个对象,从而使您可以用不同的请求对客户进行参数化。
主要解决:在软件系统中,行为请求者与行为实现者通常是一种紧耦合的关系,但某些场合,比如需要对行为进行记录、撤销或重做、事务等处理时,这种无法抵御变化的紧耦合的设计就不太合适。
解决方案:通过调用者调用接受者执行命令,顺序:调用者→接受者→命令。
优点: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("执行请求!");
}
}
}