【设计模式】之 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); } } }
相关文章推荐
- 设计模式之七——命令模式(Command)
- 设计模式之命令模式(Command Pattern)
- 深入浅出设计模式-006:命令模式(Command Pattern)
- 深入浅出设计模式——命令模式(Command Pattern)
- 设计模式 - Command 模式(命令模式)
- 设计模式学习--命令模式(command)
- php设计模式 Command(命令模式)
- 行为设计模式---命令模式(Command)
- 设计模式(14)-行为型-命令模式(Command)
- 设计模式 – 命令模式(Command)
- GOF23设计模式之 命令模式command
- java 设计模式学习笔记十二 command命令设计模式
- 23种设计模式之命令(Command)模式
- .NET设计模式-命令模式(Command Pattern)
- 设计模式初探-命令模式(COMMAND),又称动作(Action),事务(Transaction)
- 设计模式之 — Command命令模式
- 设计模式-行为型-命令模式(Command)
- Java设计模式:命令模式(Command)
- 设计模式14:Command 命令模式(行为型模式)
- 浅谈JAVA设计模式之——命令模式(Command)