Java中的23种设计模式之——简单工厂模式(3)
简单工厂模式:就是如何去实例化对象的问题,对于很容易变化的问题,应该考虑用一个单独的类来做这个创造实例的过程,这就是工厂。
简单工厂和工厂方法的区别:简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。
就像这个计算器,让客户端不用管该用哪个类的实例,只需要把“+”给工厂,工厂自动就给出了相应的实例,客户端只要去运算就可以了,不同的实例会实现不同的运算。
这里使用计算器的例子:
public class Operation { private double numberA = 0; private double numberB = 0; public double getNumberA() { return numberA; } public void setNumberA(double numberA) { this.numberA = numberA; } public double getNumberB() { return numberB; } public void setNumberB(double numberB) { this.numberB = numberB; } public double getResult() { double result = 0; return result; } }
调用函数:
public class RunOperation { public static void main(String[] args) { { //简单工厂模式 Operation operation ; // operation = OperrateFactory.createOperate("+"); // operation = OperrateFactory.createOperate("-"); // operation = OperrateFactory.createOperate("*"); operation = OperrateFactory.createOperate("+"); operation.setNumberA(1); operation.setNumberB(2); System.out.println("简单工厂模式:"+operation.getResult()); } } }
在这个例子中,只需要输入运算符,工厂就实例化出合适的对象,通过多态返回父类的方式实现了计算器的结果。而客户端只要这样调用就可以了,如下:
public class OperrateFactory { public static Operation createOperate(String operate) { Operation oper = null; if (operate.equals("+")) { oper = new OperationAdd(); } else if (operate.equals("-")) { oper = new OperationSub(); } else if (operate.equals("*")) { oper = new OperationMul(); } else if (operate.equals("/")) { oper = new OperationDiv(); } return oper; } }
加法
public class OperationAdd extends Operation{ @Override public double getResult() { double result = 0; result = getNumberA() + getNumberB(); return result; } }
除法
public class OperationDiv extends Operation{ @Override public double getResult() { double result = 0; try { if (0 == getNumberB()){ throw new Exception("除数不能为0"); } } catch (Exception e) { e.printStackTrace(); } result = getNumberA() / getNumberB(); return result; } }
乘法
public class OperationMul extends Operation { @Override public double getResult() { double result = 0; result = getNumberA() * getNumberB(); return result; } }
减法
public class OperationSub extends Operation{ @Override public double getResult() { double result = 0; result = getNumberA() - getNumberB(); return result; } }