/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package simpleFactory; /** * * @author XiaoTianCai */ //Operation運算類 public abstract class Operation { private double _numberA = 0; private double _numberB = 0; public void setNumberA(double a) { _numberA = a; } public void setNumberB(double b) { _numberB = b; } public double getNumberA() { return _numberA; } public double getNumberB() { return _numberB; } public abstract double gerResult(); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package simpleFactory; /** * * @author XiaoTianCai */ //加法類 class OperationAdd extends Operation { @Override public double gerResult() { double result = 0; result = getNumberA() + getNumberB(); return result; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package simpleFactory; /** * * @author XiaoTianCai */ //減法類 class OperationSub extends Operation { @Override public double gerResult() { double result = 0; result = this.getNumberA() - this.getNumberB(); return result; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package simpleFactory; /** * * @author XiaoTianCai */ class OperationMul extends Operation { @Override public double gerResult() { double result = 0; result = this.getNumberA() * this.getNumberB(); return result; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package simpleFactory; /** * * @author XiaoTianCai */ class OperationDiv extends Operation { @Override public double gerResult() { double result = 0; try { result = this.getNumberA() / this.getNumberB(); } catch (Exception ex) { System.out.println("除數不能爲0."); } return result; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package simpleFactory; /** * * @author XiaoTianCai */ //簡單運算工廠類 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; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package simpleFactory; /** * * @author XiaoTianCai */ public class mainTest { public static void main(String[] args) { Operation oper; /* 只須要輸入運算符號,工廠就實例化出合適的對象,聽過多態,返回父類的方式實現計算結果 */ oper = OperationFactory.createOperate("/"); //實例化對象 oper.setNumberA(12); oper.setNumberB(0); double result = oper.gerResult(); System.out.println(result); } }