Created
November 1, 2018 19:10
-
-
Save ImaginaryDevelopment/bf8e48697d56bb922eed1e5b141e9726 to your computer and use it in GitHub Desktop.
sample calculator interfacing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| void Main() | |
| { | |
| var operators = new IOperator[]{ | |
| new AdditionOperator() | |
| }; | |
| var calc = new Calculator(operators); | |
| calc.InputNumber("1"); | |
| calc.Operator = operators[0]; | |
| calc.ApplyOperator().Dump(); | |
| } | |
| // Define other methods and classes here | |
| public interface IOperator | |
| { | |
| string Name { get; } | |
| string Display { get; } | |
| int Apply(int x, int y); | |
| } | |
| public interface ICalculator | |
| { | |
| IOperator Operator { get; set; } | |
| // store the input for applying operators | |
| void InputNumber(string value); | |
| IEnumerable<IOperator> Operations { get; } | |
| // there may not be two numbers input yet | |
| int? ApplyOperator(); | |
| string Display { get; } | |
| } | |
| // sample operator | |
| public class AdditionOperator : IOperator | |
| { | |
| public int Apply(int x, int y) => x + y; | |
| public string Name => "Addition"; | |
| public string Display => "+"; | |
| } | |
| public class Calculator : ICalculator | |
| { | |
| int val1 = 0; | |
| int val2 = 0; | |
| // this could solve the val2 never getting set problem | |
| public IOperator Operator { get; set; } | |
| public IEnumerable<IOperator> Operations { get; } | |
| public int? ApplyOperator() => this.Operator?.Apply(val1,val2); | |
| public void InputNumber(string value){ | |
| int.TryParse(value,out val1); | |
| } | |
| public string Display => val1.ToString(); | |
| public Calculator(IEnumerable<IOperator> operations) => this.Operations = operations; | |
| } | |
| // bonus Factory Interface | |
| //Factory pattern | |
| public interface IMakeCalculators{ | |
| ICalculator Make(IEnumerable<IOperator> ops); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment