简单工厂模式
Operation.java
package calc; public abstract class Operation { private static double _numberA = 0; private static double _numberB = 0; static class NumberA { public static double get_numberA() { return _numberA; } public static void set_numberA(double numberA) { _numberA = numberA; } } static class NumberB { public static double get_numberB() { return _numberB; } public static void set_numberB(double numberB) { _numberB = numberB; } } public abstract double GetResult(); } class OperationAdd extends Operation { public double GetResult() { double result = 0; result = NumberA.get_numberA() + NumberB.get_numberB(); return result; } } class OperationSub extends Operation { public double GetResult() { double result = 0; result = NumberA.get_numberA() - NumberB.get_numberB(); return result; } } class OperationMul extends Operation { public double GetResult() { double result = 0; result = NumberA.get_numberA() * NumberB.get_numberB(); return result; } } class OperationDiv extends Operation { @Override public double GetResult() { double result = 0; if(NumberB.get_numberB() == 0) try { throw new Exception("not divide by zero"); } catch (Exception e) { // TODO Auto-generated catch block System.out.println("not divide by zero"); } result = NumberA.get_numberA() / NumberB.get_numberB(); return result; } }
OperationFactory.java
package calc; public class OperationFactory { public static Operation createOperate (String operator) { Operation oper = null; if(operator == "+") oper = new OperationAdd(); else if(operator == "-") oper = new OperationSub(); else if(operator == "*") oper = new OperationMul(); else if(operator == "/") oper = new OperationDiv(); return oper; } }
测试类
package calc; import java.io.*; class Calculator { // 输入两个数, 相除得结果 /** * @param args */ public static void main(String[] args) throws IOException { // BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); // System.out.println("please input a number A:"); // String A = b.readLine(); // System.out.println("please input a number B:"); // String B = b.readLine(); // int C = (new Integer(A)).intValue()/(new Integer(B)).intValue(); // System.out.println("The result is :" + C); Operation oper; oper = OperationFactory.createOperate("/"); Operation.NumberA.set_numberA(1); Operation.NumberB.set_numberB(0); double result = oper.GetResult(); System.out.println(result); } }