定義命令執行與撤銷的標準契約:
using System;
using System.Collections.Generic;
using System.Text;
namespace Pattern.Command
{
///
/// 命令(Command)角色
///
public interface ICommand
{
///
/// 執行
///
/// 操作的方法及操作的信息
string Execute();
///
/// 取消執行
///
/// 操作的方法及操作的信息
string UnExecute();
}
}
封裝接收者、動作與參數,實作執行與反向操作:
using System;
using System.Collections.Generic;
using System.Text;
namespace Pattern.Command
{
///
/// 具體命令(ConcreteCommand)角色
///
public class SqlMessageCommand : ICommand
{
///
/// 操作的方法
///
private Action _action;
///
/// Message 實體物件
///
private MessageModel _mm;
///
/// 建構函式
///
/// 操作的方法
/// Message 實體物件
public SqlMessageCommand(Action action, MessageModel mm)
{
this._action = action;
this._mm = mm;
}
///
/// 執行
///
/// 操作的方法及操作的信息
public string Execute()
{
new SqlMessage().Operation(_action, _mm);
return _action.ToString() + ":" + _mm.Message;
}
///
/// 取消執行(調用一個方法,以決定取消執行的演算法)
///
/// 操作的方法及操作的信息
public string UnExecute()
{
_action = GetUndoAction(_action);
new SqlMessage().Operation(_action, _mm);
return _action.ToString() + ":" + _mm.Message;
}
///
/// 獲得取消執行的演算法
///
/// 操作的方法
/// 反向 Action
private Action GetUndoAction(Action action)
{
Action undo;
switch (action)
{
case Action.Insert:
undo = Action.Delete;
break;
case Action.Delete:
undo = Action.Insert;
break;
default:
undo = Action.Insert;
break;
}
return undo;
}
}
}
Action(操作類型)與 MessageModel(參數),封裝執行所需完整資訊。Execute() 內部建立 SqlMessage 並呼叫 Operation(),Invoker 無需知曉 Receiver。UnExecute() 透過 GetUndoAction() 將 Insert↔Delete 互換,再執行。