|
| 1 | +package com.wonu606.calculator.strategy; |
| 2 | + |
| 3 | +import com.wonu606.calculator.calculator.Calculator; |
| 4 | +import com.wonu606.calculator.converter.Converter; |
| 5 | +import com.wonu606.calculator.model.CalculationResult; |
| 6 | +import com.wonu606.calculator.storage.Persistence; |
| 7 | +import com.wonu606.calculator.util.CalculatorMessage; |
| 8 | +import com.wonu606.calculator.validator.Validator; |
| 9 | +import com.wonu606.io.Input; |
| 10 | +import com.wonu606.io.Print; |
| 11 | +import java.util.List; |
| 12 | + |
| 13 | +public class CalculationStrategy implements CalculatorStrategy { |
| 14 | + |
| 15 | + Validator validator; |
| 16 | + Converter<String, List<String>> converter; |
| 17 | + Calculator calculator; |
| 18 | + |
| 19 | + public CalculationStrategy(Validator validator, Converter<String, List<String>> converter, |
| 20 | + Calculator calculator) { |
| 21 | + this.validator = validator; |
| 22 | + this.converter = converter; |
| 23 | + this.calculator = calculator; |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public void execute(Input input, Print printer, Persistence store) { |
| 28 | + String inputExpression = input.getInput(); |
| 29 | + if (isNotValidExpression(inputExpression)) { |
| 30 | + printer.print(CalculatorMessage.INVALID_INPUT.message); |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + List<String> convertedExpression = converter.convert(inputExpression); |
| 35 | + try { |
| 36 | + double result = calculator.calculate(convertedExpression); |
| 37 | + |
| 38 | + store.saveResult(new CalculationResult(inputExpression, result)); |
| 39 | + printCalculationResult(printer, result); |
| 40 | + } catch (ArithmeticException exception) { |
| 41 | + printer.print(exception.getMessage()); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + private static void printCalculationResult(Print printer, double result) { |
| 46 | + String message = String.valueOf(roundResultToInt(result)); |
| 47 | + if (isResultOverflow(result)) { |
| 48 | + message = CalculatorMessage.OVERFLOW_OCCURS.message; |
| 49 | + } |
| 50 | + printer.print(message); |
| 51 | + } |
| 52 | + |
| 53 | + private static int roundResultToInt(double result) { |
| 54 | + return (int) Math.round(result); |
| 55 | + } |
| 56 | + |
| 57 | + private static boolean isResultOverflow(double result) { |
| 58 | + return Double.isInfinite(result) || (isIntegerOverflow(result)); |
| 59 | + } |
| 60 | + |
| 61 | + private static boolean isIntegerOverflow(double result) { |
| 62 | + return result > Integer.MAX_VALUE; |
| 63 | + } |
| 64 | + |
| 65 | + private boolean isNotValidExpression(String inputExpression) { |
| 66 | + return !validator.isValid(inputExpression); |
| 67 | + } |
| 68 | +} |
0 commit comments