using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace CommandExample1
{
public class CommandExample1 : MonoBehaviour
{
void Start ( )
{
// Create user and let her compute
User user = new User();
// User presses calculator buttons
user.Compute('+', 100);
user.Compute('-', 50);
user.Compute('*', 10);
user.Compute('/', 2);
// 撤销4次
user.Undo(4);
// 继续执行3次
user.Redo(3);
}
}
/// <summary>
/// The 'Command' abstract class
/// </summary>
abstract class Command
{
public abstract void Execute();//执行
public abstract void UnExecute();//撤销
}
/// <summary>
/// 具体命令
/// </summary>
class CalculatorCommand : Command
{
private char _operator;//运算符
private int _operand;//运算数
private Calculator _calculator;//计算器
//构造命令的组成
public CalculatorCommand(Calculator calculator,
char @operator, int operand)
{
this._calculator = calculator;
this._operator = @operator;
this._operand = operand;
}
// Gets operator
public char Operator
{
set { _operator = value; }
}
// Get operand
public int Operand
{
set { _operand = value; }
}
// 执行
public override void Execute()
{
_calculator.Operation(_operator, _operand);
}
// 撤销
public override void UnExecute()
{
_calculator.Operation(Undo(_operator), _operand);
}
// 撤销方法
private char Undo(char @operator)
{
switch (@operator)
{
case '+': return '-';
case '-': return '+';
case '*': return '/';
case '/': return '*';
default:
throw new
ArgumentException("@operator");
}
}
}
/// <summary>
///计算器也就是命令接收者
/// </summary>
class Calculator
{
private int _curr = 0;
public void Operation(char @operator, int operand)
{
switch (@operator)
{
case '+': _curr += operand; break;
case '-': _curr -= operand; break;
case '*': _curr *= operand; break;
case '/': _curr /= operand; break;
}
Debug.Log("Current value = " + _curr+ " ( following "+ @operator+operand+" )");
}
}
/// <summary>
/// 命令请求者
/// </summary>
class User
{
// Initializers
private Calculator _calculator = new Calculator();
private List<Command> _commands = new List<Command>();
private int _current = 0;//当前命令数
//继续执行
public void Redo(int levels)
{
for (int i = 0; i < levels; i++)
{
if (_current < _commands.Count - 1)
{
Command command = _commands[_current++];
command.Execute();
}
}
}
public void Undo(int levels)
{
Debug.Log("\n---- Undo "+ levels + " levels");
//拿到最后一条命令开始撤销
for (int i = 0; i < levels; i++)
{
if (_current > 0)
{
Command command = _commands[--_current] as Command;
command.UnExecute();
}
}
}
public void Compute(char @operator, int operand)
{
// 实例化命令并执行
Command command = new CalculatorCommand(
_calculator, @operator, operand);
command.Execute();
// 加入命令列表
_commands.Add(command);
_current++;
}
}
}