-1
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class App 
{
    public static void main( String[] args ) throws Exception
    {   

    enter code here
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println( "Enter 2 numbers:" );
    float num1 = Float.parseFloat(br.readLine());
    float num2 = Float.parseFloat(br.readLine());
    System.out.println("Select option : 1.Addition 2.Substraction 3.Multiplication 4.Division");
    int option = Integer.parseInt(br.readLine());
    switch(option) {
    case 1:System.out.print("result: "+(num1+num2));break;
    case 2:System.out.print("result: "+(num1-num2));break;
    case 3:System.out.print("result: "+(num1*num2));break;
    case 4:System.out.print("result: "+(num1/num2));break;
    }
        
   }
}

我在 java 中有简单的计算器代码,需要在这个 Calcualtor 程序上实现 solid、kiss、dry 和 yagin 原则。

4

1 回答 1

0

设计问题没有固定的解决方案,但您可以在此处应用策略模式。像这样的东西应该适合你:

  public interface CalcStrategy 
    {
       public int execute(int x, int y);
    }
    
    public class AdditionStrategy implements CalcStrategy {
    
        @Override
        public int execute(int x, int y) {
            return x + y;
        }
    }
    
    public class MultiplicationStrategy implements CalcStrategy {
    
        @Override
        public int execute(int x, int y) {
            return x * y;
        }
    }
    
    public class OperationHandler {
        CalcStrategy calcStrategy;
    
        public OperationHandler(CalcStrategy calcStrategy) {
            this.calcStrategy= calcStrategy;
        }
    
        public int execute(int a, int b) {
            return this.calcStrategy.execute(a, b);
        }
    
    }
    
public class App 
{
    public static void main(String[] args) {
    OperationHandler handler = new OperationHandler(new MultiplicationStrategy());
            int x = handler.execute(10, 20);
    handler = new OperationHandler(new AdditionStrategy());
            int y = handler.execute(10, 20);
    }
}
于 2021-07-13T08:30:03.777 回答