namespace CommandPatterns
{
using System;
using System.Collections;
abstract class Command
{
#region
abstract public void Execute();
abstract public void UnExecute();
#endregion
}
class CalculatorCommand : Command
{
#region
private char op;
int operand;
Calculator calculator;
#endregion
public CalculatorCommand(Calculator calculator,char op,int operand)
{
this.calculator = calculator;
this.op = op;
this.operand = operand;
}
public char Operator
{
get { return op; }
set { op = value; }
}
public int Operand
{
get { return operand; }
set { operand = value; }
}
public override void UnExecute()
{
calculator.Operation(Undo(op),operand);
//throw new NotImplementedException();
}
public override void Execute()
{
calculator.Operation(op, operand);
//throw new NotImplementedException();
}
private char Undo(char op)
{
char undo=' ';
switch (op)
{
case '+': undo = '-';
break;
case '-': undo = '+';
break;
case '*': undo = '/';
break;
case '/': undo = '*';
break;
default: break;
}
return undo;
}
}
//接收者
class Calculator
{
private int total = 0;
public void Operation(char op, int operand)
{
switch (op)
{
case'+':total+=operand;
break;
case '-': total -= operand;
break;
case '*': total *= operand;
break;
case '/': total /= operand;
break;
default :break;
}
Console.WriteLine("Total ={0} (following {1} {2})", total, op, operand);
}
}
// 调用者
class User
{
#region
private Calculator calculator = new Calculator();
private ArrayList commands = new ArrayList();
private int current=0;
#endregion
public void Redo(int levels)
{
Console.WriteLine("-----Redo{0} Levels",levels);
for (int i = 0; i < levels; i++)
{
if (current < commands.Count - 1)
((Command)commands[current++]).Execute();
}
}
public void Undo(int levels)
{
Console.WriteLine("-----Undo{0} Levels",levels);
for (int i = 0; i < levels; i++)
if (current > 0)
((Command)commands[--current]).UnExecute();
}
public void Computer(char op, int operand)
{
Command command = new CalculatorCommand(calculator, op, operand);
command.Execute();
commands.Add(command);
current++;
}
}
public class CommandApp
{
public static void Main()
{
User user = new User();
user.Computer('+',100);
user.Computer('-',50);
user.Computer('*',10);
user.Computer('/',2);
user.Undo(4);
user.Redo(3);
Console.ReadKey();
}
}
}
命令模式示例1
最新推荐文章于 2022-05-17 22:46:30 发布