ICommand
using System;
using System.Collections.Generic;
using System.Text;
namespace Pattern.Command
{
/**//// <summary>
/// 命令(Command)角色
/// </summary>
public interface ICommand
{
/**//// <summary>
/// 執行
/// </summary>
/// <returns>操作的方法及操作的信息</returns>
string Execute();
/**//// <summary>
/// 取消執行
/// </summary>
/// <returns>操作的方法及操作的信息</returns>
string UnExecute();
}
}
SqlMessageCommand
using System;
using System.Collections.Generic;
using System.Text;
namespace Pattern.Command
{
/**//// <summary>
/// 具體命令(ConcreteCommand)角色
/// </summary>
public class SqlMessageCommand : ICommand
{
/**//// <summary>
/// 操作的方法
/// </summary>
private Action _action;
/**//// <summary>
/// Message實體對象
/// </summary>
private MessageModel _mm;
/**//// <summary>
/// 構造函數
/// </summary>
/// <param name="action">操作的方法</param>
/// <param name="mm">Message實體對象</param>
public SqlMessageCommand(Action action, MessageModel mm)
{
this._action = action;
this._mm = mm;
}
/**//// <summary>
/// 執行
/// </summary>
/// <returns>操作的方法及操作的信息</returns>
public string Execute()
{
new SqlMessage().Operation(_action, _mm);
return _action.ToString() + ":" + _mm.Message;
}
/**//// <summary>
/// 取消執行(調用一個方法,以決定取消執行的算法)
/// </summary>
/// <returns>操作的方法及操作的信息</returns>
public string UnExecute()
{
_action = GetUndoAction(_action);
new SqlMessage().Operation(_action, _mm);
return _action.ToString() + ":" + _mm.Message;
}
/**//// <summary>
/// 獲得取消執行的算法
/// </summary>
/// <param name="action">操作的方法</param>
/// <returns></returns>
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;
}
}
}