package com.maom.design.D_04_Test_Factory_Calculator;
import java.util.Scanner;
/**
* @Title: D_04_Test_Factory_Calculator
* @Description: 04_工厂模式应用_计算器
* @Author maohb
* @Version 1.0
*/
public class D_04_Test_Factory_Calculator {
public static void main(String[] args) {
//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 result = 0;
double num1 = Double.parseDouble(strNum1);
double num2 = Double.parseDouble(strNum2);
//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);
}
}
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();
}
interface OperationFactory {
public Operation getOperation();
}
class AddOperation extends Operation {
public double getResult() {
double result = this.getNum1() + this.getNum2();
return result;
}
}
class AddOperationFactory implements OperationFactory{
public Operation getOperation() {
return new AddOperation();
}
}
设计模式笔记_04_工厂模式应用_计算器
最新推荐文章于 2024-09-10 17:07:09 发布