首页 > 代码库 > 简单工厂模式
简单工厂模式
/* * 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); }}
简单工厂模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。