为了支持命令的撤销、重做等功能,命令的使用者和执行者应该具有较低的耦合。命令模式通过将“命令”抽象化而实现了使用者和实现者之间的松耦合。
ICommand:
Code
public interface ICommand
{
void Execute();
void Undo();
}
public interface ICommand
{
void Execute();
void Undo();
}
CommandOne:
Code
class CommandOne:ICommand
{
private CommandRecevier _recevier;
public CommandOne(CommandRecevier recevier)
{
_recevier = recevier;
}
#region ICommand 成员
public void Execute()
{
_recevier.ActionOne();
}
public void Undo()
{
_recevier.UndoActionOne();
}
#endregion
}
class CommandOne:ICommand
{
private CommandRecevier _recevier;
public CommandOne(CommandRecevier recevier)
{
_recevier = recevier;
}
#region ICommand 成员
public void Execute()
{
_recevier.ActionOne();
}
public void Undo()
{
_recevier.UndoActionOne();
}
#endregion
}
CommandTwo:
Code
class CommandTwo:ICommand
{
private CommandRecevier _recevier;
public CommandTwo(CommandRecevier recevier)
{
_recevier = recevier;
}
#region ICommand 成员
public void Execute()
{
_recevier.ActionTwo();
}
public void Undo()
{
_recevier.UndoActionTwo();
}
#endregion
}
class CommandTwo:ICommand
{
private CommandRecevier _recevier;
public CommandTwo(CommandRecevier recevier)
{
_recevier = recevier;
}
#region ICommand 成员
public void Execute()
{
_recevier.ActionTwo();
}
public void Undo()
{
_recevier.UndoActionTwo();
}
#endregion
}
Invoker:
Code
class Invoker
{
private List<ICommand> _commandList = new List<ICommand>();
private Stack<ICommand> _commandStack = new Stack<ICommand>();
private ICommand _undoCommand;
public void SetCommand(ICommand command)
{
_commandList.Add(command);
}
public void ExecuteCommand()
{
foreach (var item in _commandList)
{
item.Execute();
_commandStack.Push(item);
}
}
public void Undo()
{
_commandStack.Pop().Undo();
}
}
class Invoker
{
private List<ICommand> _commandList = new List<ICommand>();
private Stack<ICommand> _commandStack = new Stack<ICommand>();
private ICommand _undoCommand;
public void SetCommand(ICommand command)
{
_commandList.Add(command);
}
public void ExecuteCommand()
{
foreach (var item in _commandList)
{
item.Execute();
_commandStack.Push(item);
}
}
public void Undo()
{
_commandStack.Pop().Undo();
}
}
Clinet:
Code
public class Clinet
{
public static void Main()
{
Invoker invoker = new Invoker();
CommandRecevier recevier = new CommandRecevier();
invoker.SetCommand(new CommandOne(recevier));//可以通过工厂模式获得
invoker.SetCommand(new CommandTwo(recevier));//可以通过工厂模式获得
invoker.ExecuteCommand();
invoker.Undo();
invoker.Undo();
Console.Read();
}
}
public class Clinet
{
public static void Main()
{
Invoker invoker = new Invoker();
CommandRecevier recevier = new CommandRecevier();
invoker.SetCommand(new CommandOne(recevier));//可以通过工厂模式获得
invoker.SetCommand(new CommandTwo(recevier));//可以通过工厂模式获得
invoker.ExecuteCommand();
invoker.Undo();
invoker.Undo();
Console.Read();
}
}
结果: