Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.61 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace Command {
  5. public class Calculator {
  6. private int _curr = 0;
  7.  
  8. public int CurrentResult { get => _curr; set => _curr = value; }
  9.  
  10. public int Operate (char @operator, int operand) {
  11. // possibility to use interpreter pattern
  12. switch (@operator) {
  13. case '+':
  14. CurrentResult += operand;
  15. break;
  16. case '-':
  17. CurrentResult -= operand;
  18. break;
  19. case '*':
  20. CurrentResult *= operand;
  21. break;
  22. case '/':
  23. CurrentResult /= operand;
  24. break;
  25. }
  26.  
  27. return CurrentResult;
  28. }
  29. }
  30. }
  31.  
  32. namespace Command {
  33. public class CalculatorClient {
  34. private Calculator calculator = new Calculator ();
  35. private Stack<Command> _commands = new Stack<Command> ();
  36.  
  37. public int Result { get => calculator.CurrentResult; }
  38.  
  39. public double Compute (char @operator, int operand) {
  40. var command = new CalculatorCommand (calculator, @operator, operand);
  41. _commands.Push (command);
  42. return command.Execute ();
  43. }
  44.  
  45. public double Undo () {
  46. return _commands.Pop ().UnExecute ();
  47. }
  48. }
  49. }
  50.  
  51. namespace Command {
  52. public class CalculatorCommand : Command {
  53. private readonly Calculator calculator;
  54. private readonly char @operator;
  55. private readonly int operand;
  56.  
  57. public CalculatorCommand (Calculator calculator, char @operator, int operand) {
  58. this.calculator = calculator;
  59. this.@operator = @operator;
  60. this.operand = operand;
  61. }
  62.  
  63. public override double Execute () {
  64. return calculator.Operate (@operator, operand);
  65. }
  66.  
  67. public override double UnExecute () {
  68. return calculator.Operate (GetUndoOperator (@operator), operand);
  69. }
  70.  
  71. private char GetUndoOperator (char @operator) {
  72. switch (@operator) {
  73. case '+':
  74. return '-';
  75. case '-':
  76. return '+';
  77. case '*':
  78. return '/';
  79. case '/':
  80. return '*';
  81. default:
  82. throw new ArgumentException (nameof (@operator) + "is not found");
  83. }
  84. }
  85. }
  86. }
  87.  
  88. namespace Command {
  89. public abstract class Command {
  90. public abstract double Execute ();
  91. public abstract double UnExecute ();
  92. }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement