代码无错就是优? ——简单工厂模式(计算器)

要求体现面向对象的思想
UML图:

代码无错就是优?  ——简单工厂模式(计算器)
Operation类

public class Operation {

static double numberA;
static double numberB;

public static double getNumberA() {
	return numberA;
}

public static void setNumberA(double numberA) {
	Operation.numberA = numberA;
}

public static double getNumberB() {
	return numberB;
}

public static void setNumberB(double numberB) {
	Operation.numberB = numberB;
}

public double getResult() {
	double result = 0;
	return result;
}

}

加法类

public class OperationAdd extends Operation{

public double getResult(){
	double result = 0;
	result = numberA + numberB;
	return result;
	
}

}

减法类

public class OperationSub extends Operation{
public double getResult(){
double result = 0;
result = numberA - numberB;
return result;
}
}

乘法类

public class OperationMul extends Operation{
public double getResult(){
double result = 0;
result = numberA * numberB;
return result;
}
}

除法类

public class OperationDiv extends Operation{
public double getResult(){
double result = 0;
result = numberA / numberB;
return result;
}
}

简单运算工厂类

public class OperationFactory {
public static Operation createOperate(String operate){
Operation oper = null;
switch(operate){
case “+”:
oper = new OperationAdd();
break;
case “-”:
oper = new OperationSub();
break;
case “*”:
oper = new OperationMul();
break;
case “/”:
oper = new OperationDiv();
break;
}
return oper;
}
}

Main类

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	Scanner sc = new Scanner(System.in);
	System.out.println("请输入数字A:");
	double a = sc.nextDouble();
	System.out.println("请输入运算符:");
	String operator = sc.next();
	System.out.println("请输入数字c:");
	double c = sc.nextDouble();
	Operation oper = OperationFactory.createOperate(operator);
	oper.setNumberA(a);
	oper.setNumberB(c);
	System.out.println("结果:"+oper.getResult());
}

}

上一篇:巧填运算符号——穷举法(枚举法)


下一篇:C++ 代码性能优化 -- 循环分割提高并行性