package com.example.demo03;
public class AddOperation extends Operation {
@Override
public double getResult() {
double result = this.getNum1() + this.getNum2();
return result;
}
}
package com.example.demo03;
public class AddOperationFactory implements OperationFactory {
@Override
public Operation getOperation() {
return new AddOperation();
}
}
package com.example.demo03;
public abstract class Operation {
private double num1;
private double num2;
public double getNum1() {
return num1;
}
public void setNum1(double num1) {
this.num1 = num1;
}
public double getNum2() {
return num2;
}
public void setNum2(double num2) {
this.num2 = num2;
}
public abstract double getResult();
}
package com.example.demo03;
public interface OperationFactory {
public Operation getOperation();
}
package com.example.demo03;
public class SubtractionOperation extends Operation {
@Override
public double getResult() {
double result = this.getNum1() - this.getNum2();
return result;
}
}
package com.example.demo03;
import java.util.Scanner;
import org.junit.Test;
public class MainClass {
@SuppressWarnings("resource")
@Test
public void test02(){
//1.接受控制台输入
System.out.println("---计算器程序---");
System.out.println("输入第一个操作数:");
Scanner scanner = new Scanner(System.in);
String strNum1 = scanner.nextLine();
System.out.println("输入运算符:");
String oper = scanner.nextLine();
System.out.println("输入第二个操作数:");
String strNum2 = scanner.nextLine();
double num1 = Double.parseDouble(strNum1);
double num2 = Double.parseDouble(strNum2);
double result = 0;
//2.进行运算
if ("+".equals(oper)) {
OperationFactory factory = new AddOperationFactory();
Operation operation = factory.getOperation();
operation.setNum1(num1);
operation.setNum2(num2);
result = operation.getResult();
}
//3.返回结果
System.out.println(strNum1 + oper + strNum2 + "=" + result);
}
}