设计模式--简单工厂
简单工厂模式, 就是建立一个工厂类,对实现了同一接口的一些类进行实例的创建。
下面以一个计算器的实现举例,简单工厂模式的场景描述:
+-*/ 等运算不希望混合在一起,因为以后需要扩展的时候,比如说增加一个平方的运算,不希望在同一个方法里面或者同一个类里面去修改,因为这样子的危险性太高了,如果因为增加一个平方的运算,从而影响之前的运算,那肯定不是我们所希望的,所以有简单工厂模式的出现,下面主要是以贴代码为主:
测试AppMain
public static void main(String[] args) throws Exception {
Operation operation = OperationFactory.createOperate("-");
operation.setNumberA(3);
operation.setNumberB(2);
double result = operation.getResult();
System.out.println(result);
}
简单工厂 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;
}
case "sqr":
{
oper = new OperationSqr();
break;
}
case "sqrt":
{
oper = new OperationSqrt();
break;
}
case "+/-":
{
oper = new OperationReverse();
break;
}
}
return oper;
}
运算的抽象操作 Operation
public abstract 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;
}
/**
* 抽象获取结果方法,子类实现
* @return
* @throws Exception
*/
public abstract double getResult() throws Exception;
}
加法实现抽象 OperationAdd
public class OperationAdd extends Operation{
@Override
public double getResult() {
double result = 0;
result = getNumberA() + getNumberB();
System.out.println(result);
return result;
}
}
…….
其他的运算一样,具体不贴码了。