1.运算接口
public interface Operation { public double getResult(double NumberA , double NumberB); }
2.加减乘除类
public class OperationAdd implements Operation { @Override public double getResult(double NumberA, double NumberB) { return NumberA + NumberB; } } public class OperationSub implements Operation { @Override public double getResult(double NumberA, double NumberB) { return NumberA - NumberB; } } public class OperationMul implements Operation { @Override public double getResult(double NumberA, double NumberB) { return NumberA * NumberB; } } public class OperationDiv implements Operation { @Override public double getResult(double NumberA, double NumberB) { if(NumberB==0) try { throw new Exception("除数不能为0"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return NumberA / NumberB; } }
3.简单运算工厂类
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; } }
4.测试类
public class test { public static void main(String[] args){ Operation oper; oper = OperationFactory.createOperate("+"); System.out.println(oper.getResult(1, 2)); } }