visit
public interface ICommand
{
void Execute();
}
public class AdditionCommand : ICommand
{
private readonly Calculator _calculator;
private readonly int _operand;
public AdditionCommand(Calculator calculator, int operand)
{
_calculator = calculator;
_operand = operand;
}
public void Execute()
{
_calculator.Add(_operand);
}
}
public class SubtractionCommand : ICommand
{
private readonly Calculator _calculator;
private readonly int _operand;
public SubtractionCommand(Calculator calculator, int operand)
{
_calculator = calculator;
_operand = operand;
}
public void Execute()
{
_calculator.Subtract(_operand);
}
}
public class MultiplicationCommand : ICommand
{
private readonly Calculator _calculator;
private readonly int _operand;
public MultiplicationCommand(Calculator calculator, int operand)
{
_calculator = calculator;
_operand = operand;
}
public void Execute()
{
_calculator.Multiply(_operand);
}
}
public class DivisionCommand : ICommand
{
private readonly Calculator _calculator;
private readonly int _operand;
public DivisionCommand(Calculator calculator, int operand)
{
_calculator = calculator;
_operand = operand;
}
public void Execute()
{
_calculator.Divide(_operand);
}
}
}
public class Calculator
{
private int _result;
public void Add(int operand)
{
_result += operand;
}
public void Subtract(int operand)
{
_result -= operand;
}
public void Multiply(int operand)
{
_result *= operand;
}
public void Divide(int operand)
{
if (operand != 0)
{
_result /= operand;
}
}
public int GetResult()
{
return _result;
}
}
public class CalculatorInvoker
{
private ICommand _command;
public void SetCommand(ICommand command)
{
_command = command;
}
public void ExecuteCommand()
{
_command.Execute();
}
}
Now, let us see how these classes can perform arithmetic operations.
static void Main(string[] args) {
Calculator calculator = new Calculator();
CalculatorInvoker invoker = new CalculatorInvoker();
// Create commands for arithmetic operations
AdditionCommand additionCommand = new AdditionCommand(calculator, 5);
SubtractionCommand subtractionCommand = new SubtractionCommand(calculator, 3);
MultiplicationCommand multiplicationCommand = new MultiplicationCommand(calculator, 2);
DivisionCommand divisionCommand = new DivisionCommand(calculator, 4);
// Execute commands using invoker
invoker.SetCommand(additionCommand);
invoker.ExecuteCommand();
invoker.SetCommand(subtractionCommand);
invoker.ExecuteCommand();
invoker.SetCommand(multiplicationCommand);
invoker.ExecuteCommand();
invoker.SetCommand(divisionCommand);
invoker.ExecuteCommand();
// Get result from calculator
int result = calculator.GetResult();
Console.WriteLine("Result: " + result); // Output: Result: 1
}
Also published