一、什么是命令模式
它就是把对象和行为分离,它有4个角色:
- 发布者:接收命令。
- 调用者:把多个命令聚合在一起。
- 执行者:最终操作实现的地方。
- 具体命令:具体执行的操作。
二、命令模式的作用
实现异步队列,数据恢复,命令撤销。
三、命令模式的使用场景
设置快捷键,比如A键代表什么,在这个场景可能是“A”,在别的场景可能就是“左”之类的。。
像在网上买票的系统,都是先下一个订单,保存买票的命令进行排队,然后在由另外的服务去完成出票的操作,这样可以提升响应速度,因为是异步的,下单的操作会很快,出票的操作会慢一些。
四、如何实现命令模式
同一个按键,不同的命令模式其结果就不同,就像软件设置不同的快捷键一样。。
主程序:
namespace Command
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("请输入 w、s、a、d ");
string input = Console.ReadLine();
string action = ConfigurationManager.AppSettings[input];
BaseCommand command = (BaseCommand)Activator.CreateInstance(action.Split(',')[1], action.Split(',')[0]).Unwrap();
Console.WriteLine("请选择模板 1、2 ");
input = Console.ReadLine();
string receiverMode = ConfigurationManager.AppSettings[input];
IReceiver receiver = (IReceiver)Activator.CreateInstance(receiverMode.Split(',')[1], receiverMode.Split(',')[0]).Unwrap();
command.SetReiceiver(receiver);
Invoker invoker = new Invoker(command);
invoker.Excute();
Console.WriteLine("");
}
}
}
}
发布者基类BaseCommand.cs:
namespace Command
{
public abstract class BaseCommand
{
public IReceiver _Receiver
{
get;
private set;
}
public void SetReiceiver(IReceiver receiver)
{
this._Receiver = receiver;
}
public abstract void Excute();
}
}
发布者子类:
//ACommand.cs
namespace Command
{
public class ACommand : BaseCommand
{
public override void Excute()
{
this._Receiver.PressW();
}
}
}
//DCommand.cs
namespace Command
{
public class DCommand : BaseCommand
{
public override void Excute()
{
this._Receiver.PressD();
}
}
}
//SCommand.cs
namespace Command
{
public class SCommand : BaseCommand
{
public override void Excute()
{
this._Receiver.PressS();
}
}
}
//WCommand.cs
namespace Command
{
public class WCommand : BaseCommand
{
public override void Excute()
{
this._Receiver.PressW();
}
}
}
调用者Invoker.cs:
namespace Command
{
public class Invoker
{
private BaseCommand _BaseCommand = null;
public Invoker(BaseCommand baseCommand)
{
this._BaseCommand = baseCommand;
}
public void Excute()
{
this._BaseCommand.Excute();
}
}
}
执行者IReceiver.cs:
namespace Command
{
public interface IReceiver
{
void PressW();
void PressS();
void PressA();
void PressD();
}
}
具体命令:
//ReceiverOne.cs
namespace Command
{
public class ReceiverOne : IReceiver
{
public void PressW()
{
//可以把命令记录下来
Console.WriteLine("输入了W");
}
public void PressS()
{
Console.WriteLine("输入了S");
}
public void PressA()
{
Console.WriteLine("输入了A");
}
public void PressD()
{
Console.WriteLine("输入了D");
}
}
}
//ReceiverTwo.cs
namespace Command
{
public class ReceiverTwo : IReceiver
{
public void PressW()
{
//可以把命令记录下来
Console.WriteLine("上");
}
public void PressS()
{
Console.WriteLine("下");
}
public void PressA()
{
Console.WriteLine("左");
}
public void PressD()
{
Console.WriteLine("右");
}
}
}
描述可能不太准确,实现方法肯定是对的,大概意思理解一下就好。。。
以上为本章所有内容。
完。