# 命令模式
属于行为型模式。
将一个请求封装成一个对象,从而可以用不同的请求对客户进行参数化,对请求排队或记录请求日志,以及支持可撤销的操作。
优点:
- 能够比较容易地设计一个命令队列
- 在需要的情况下,可以较容易地将命令记入日志
- 允许接收请求的一方决定是否要否决请求
- 可以容易地实现对请求的撤销和重做
- 容易扩展
# 类图
# 代码
# 命令类
| namespace BehavioralPatterns_CommandPattern |
| { |
| |
| |
| |
| public abstract class Command |
| { |
| public abstract string CommandName { get; } |
| |
| |
| |
| |
| protected Executor MainExecutor; |
| |
| public Command(Executor executor) |
| { |
| MainExecutor = executor; |
| } |
| |
| |
| |
| |
| public virtual void Execute() |
| { |
| MainExecutor.Execute(this); |
| } |
| } |
| } |
| namespace BehavioralPatterns_CommandPattern |
| { |
| public class Command_0 : Command |
| { |
| public override string CommandName => "Command_0"; |
| |
| public Command_0(Executor executor) : base(executor) { } |
| } |
| } |
| namespace BehavioralPatterns_CommandPattern |
| { |
| public class Command_1 : Command |
| { |
| public override string CommandName => "Command_1"; |
| |
| public Command_1(Executor executor) : base(executor) { } |
| |
| } |
| } |
# 执行命令的类
| namespace BehavioralPatterns_CommandPattern |
| { |
| public class Executor |
| { |
| |
| |
| |
| public void Execute(Command command) |
| { |
| Console.WriteLine("Action: " + command.CommandName); |
| } |
| } |
| } |
# 接收请求的类
| namespace BehavioralPatterns_CommandPattern |
| { |
| |
| |
| |
| public class Receiver |
| { |
| |
| |
| |
| private List<Command> CommandList; |
| |
| public Receiver() |
| { |
| CommandList = new List<Command>(); |
| } |
| |
| |
| |
| |
| |
| public void AddCommand(Command command) |
| { |
| |
| if (CommandList.Count >= 2) |
| { |
| |
| Console.WriteLine("Time: " + DateTime.Now + "\tRefuseAddCommand: " + command.CommandName); |
| } |
| else |
| { |
| |
| CommandList.Add(command); |
| |
| |
| Console.WriteLine("Time: " + DateTime.Now + "\tAddCommand: " + command.CommandName); |
| } |
| } |
| |
| |
| |
| |
| |
| public void RemoveCommand(Command command) |
| { |
| |
| CommandList.Remove(command); |
| |
| |
| Console.WriteLine("Time: " + DateTime.Now + "\tCancleCommand: " + command.CommandName); |
| } |
| |
| |
| |
| |
| public void ExcuteCommand() |
| { |
| foreach (var item in CommandList) |
| { |
| item.Execute(); |
| } |
| } |
| } |
| } |
# 测试
| namespace BehavioralPatterns_CommandPattern |
| { |
| public class Program |
| { |
| private static void Main() |
| { |
| Executor executor = new Executor(); |
| Receiver receiver = new Receiver(); |
| Command command_0 = new Command_0(executor); |
| Command command_1 = new Command_1(executor); |
| |
| receiver.AddCommand(command_0); |
| receiver.AddCommand(command_1); |
| receiver.AddCommand(command_1); |
| |
| receiver.RemoveCommand(command_1); |
| |
| Console.WriteLine(); |
| receiver.ExcuteCommand(); |
| } |
| } |
| } |
运行结果:
Time: 2023/7/29 20:21:27 AddCommand: Command_0
Time: 2023/7/29 20:21:27 AddCommand: Command_1
Time: 2023/7/29 20:21:27 RefuseAddCommand: Command_1
Time: 2023/7/29 20:21:27 CancleCommand: Command_1
Action: Command_0