您的位置:首页 > 其它

【设计模式】之 Command 命令模式

2012-03-05 09:39 337 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace DesignFactory.Command
{
class CommandPattern
{
}

abstract class Command
{
abstract public void Execute();
abstract public void UnExecute();
}

class Calculator
{
private int total = 0;
public void Operation(char @operator, int operand)
{
switch (@operator)
{
case '+' : total += operand; break;
case '-': total -= operand; break;
case '*': total *= operand; break;
case '/': total /= operand; break;
}

Console.WriteLine("Total={0}(following {1}{2}",total,@operator,operand);
}
}

class CalculatorCommand : Command
{
char @operator;
int operand;
Calculator calculator;

public CalculatorCommand(Calculator calculator, char @operator, int operand)
{
this.calculator = calculator;
this.@operator = @operator;
this.operand = operand;
}

public char Operator
{
set { @operator = value; }
}
public char 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)
{
char undo = ' ';
switch(@operator)
{
case '+' : undo='-'; break;
case '-': undo='+'; break;
case '*':undo='/'; break;
case '/': undo='*'; break;
}

return undo;
}

}

class User
{
private Calculator calculator = new Calculator();
private ArrayList commands = new ArrayList();
private int current = 0;

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 < commands.Count - 1)
{
((Command)commands[--current]).Execute();
}
}
}

public void Compute(char @operator, int operand)
{
Command command = new CalculatorCommand(calculator, @operator, operand);
command.Execute();

commands.Add(command);
current++;
}

}

public class Client
{
public static void Main(string[] args)
{
User user = new User();
user.Compute('+', 100);
user.Compute('-', 100);
user.Compute('*', 100);
user.Compute('/', 100);

user.Undo(4);
user.Redo(4);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: