命令模式簡介
把一個請求或者操作封裝在命令對象中。命令模式允許系統使用不同的請求把客戶端參數化,對請求排隊或者記錄請求日誌,可以提供命令的撤銷和恢復功能。
命令模式角色:
- Receiver 也就是最終要執行的命令【】;
- Command 將Receiver命令的方法進行抽象,抽象成一個Exectue()方法;
- ConcreteCommand 將Receiver中的每一個命令生成一個具體的子類;
- Invoker 命令的調用,給Client進行調用,同時呢這個類要實現命令的執行、恢復、撤銷等操作;
- Client
通過調用者調用接受者執行命令,順序:調用者→接受者→命令。
將一個請求封裝成一個對象,從而使您可以用不同的請求對客戶進行參數化。
C# 命令模式Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommandPattern
{
class Program
{
static void Main(string[] args)
{
Receiver receiver = new Receiver();
ICommand addCommand = new AddCommand(receiver);
ICommand removeCommand = new RemoveCommand(receiver);
Invoke invoke = new Invoke();
// 添加命令
invoke.SetCommand(addCommand);
invoke.SetCommand(removeCommand);
// 執行命令集合
invoke.Execute();
Console.WriteLine("-------------------");
// 撤銷命令
invoke.Undo();
// 執行命令集合
invoke.Execute();
}
}
public interface ICommand
{
void Execute();
}
public class Receiver
{
public void Add()
{
Console.WriteLine("運行Add()...");
}
public void Remove()
{
Console.WriteLine("運行Remove()...");
}
}
public class AddCommand : ICommand
{
private Receiver receiver = null;
public AddCommand(Receiver receiver)
{
this.receiver = receiver;
}
public void Execute()
{
this.receiver.Add();
}
}
public class RemoveCommand : ICommand
{
private Receiver receiver = null;
public RemoveCommand(Receiver receiver)
{
this.receiver = receiver;
}
public void Execute()
{
this.receiver.Remove();
}
}
public class Invoke
{
private List<ICommand> commandList = new List<ICommand>();
public void SetCommand(ICommand command)
{
commandList.Add(command);
}
public void Execute()
{
foreach (var command in commandList)
{
command.Execute();
}
}
/// <summary>
/// 從命令列表中刪除最後一條命令
/// </summary>
public void Undo()
{
this.commandList.RemoveAt(this.commandList.Count - 1);
}
}
}
測試結果:
系統需要支持命令的撤銷(Undo)操作和恢復(Redo)操作,也可以考慮使用命令模式,見命令模式的擴展。 | |
---|---|
參考資料
https://www.bilibili.com/video/av78515440?p=17
更多: