//operation.java
import java.math.*;
abstract class operation { //抽象类,抽象出共同属性
private double numberA = 0;
private double numberB = 0;
public double getnumberA(){
return numberA;
}
public void setnumberA(double newA){
numberA = newA;
}
public double getnumberB(){
return numberB;
}
public void setnumberB(double newB){
numberB = newB;
}
abstract public double getResult() throws Exception;
}
class operationAdd extends operation{ //子类重写父类中的抽象方法
public double getResult(){ //重写抽象类方法,前面不用加override,,中毒太深!!!
double resu = 0;
resu = getnumberA() + getnumberB();
return resu;
}
}
class operationSub extends operation{
public double getResult(){
double resu = 0;
resu = getnumberA() - getnumberB();
return resu;
}
}
class operationMul extends operation{
public double getResult(){
double resu = 0;
resu = getnumberA() * getnumberB();
return resu;
}
}
class operationDiv extends operation{
public double getResult() throws Exception{
double resu = 0;
if (getnumberB() == 0){
throw new Exception("Divider can't be zero...");
}
resu = getnumberA() / getnumberB();
return resu;
}
}
class operationSqrt extends operation{
public double getResult() throws Exception{
double resu = 0;
resu = Math.sqrt(getnumberA());
return resu;
}
}
operationFactory.java
import java.util.Scanner;
/*
* 简单工厂模式:定义一个用于创建对象的接口。
* 一个工厂类处于对产品类实例化调用的中心位置上,它决定哪一个产品类应当被实例化。
*
*/
//如果要增加新的运算,只需在工厂类中添加分支,然后创建相应的运算子类,这样代码易于扩展,易于维护。
public class operationFactory {
public static operation createOperation(String operate){
operation op = null;
switch(operate){
case "+":
op = new operationAdd();
break;
case "-":
op = new operationSub();
break;
case "*":
op = new operationMul();
break;
case "/":
op = new operationDiv();
break;
case "//": //求一个数的平方根
op = new operationSqrt();
break;
}
return op;
}
public static void main(String[] args) throws Exception{
System.out.println("Input the operation:");
Scanner scan = new Scanner(System.in);
String op = scan.nextLine();
operation oper = createOperation(op);
System.out.println("Input the two number:");
double num1=scan.nextDouble();
oper.setnumberA(num1);
double num2=scan.nextDouble();
oper.setnumberB(num2);
double resu=oper.getResult();
System.out.println("result:" + resu);
}
}