📄 class1.cs
字号:
using System;
using System.Collections;
//抽象命令类
abstract class Command
{
abstract public void Execute();
abstract public void UnExecute();
}
//具体命令类
class CalculatorCommand : Command
{
private 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 int Operand
{
set{ operand = value; }
}
override public void Execute()
{
calculator.Operation( @operator, operand );
}
override public 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 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 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 > 0 )
((Command)commands[ --current ]).UnExecute();
}
public void Compute( char @operator, int operand )
{
//生成命令并且执行它
Command command = new CalculatorCommand(
calculator, @operator, operand );
command.Execute();
//在取消列中增加这个命令
commands.Add( command );
current++;
}
}
/// <summary>
///命令应用测验
/// </summary>
public class CommandApp
{
public static void Main( string[] args )
{
//生成用户,让它来计算
User user = new User();
user.Compute( '+', 100 );
user.Compute( '-', 50 );
user.Compute( '*', 10 );
user.Compute( '/', 2 );
// 取消,重做一些命令
user.Undo( 4 );
user.Redo( 3 );
Console.Read();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -