什么是简单工厂模式
简单工厂模式: 比如要实现一个做运算的功能(加减乘除)
父类:Operation
子类:OperationAdd、OperationSub、OperationMul、OperationDiv
简单工厂类的核心方法是:Operation CreateOperation(String),让其通过多态,创造相应实例。
使用场景: 比如实现运算功能的时候,需求可能会很多,很容易变化。
好处: 增加各种复杂的运算时,工厂类可以封装变化,让客户端更加方便的实现运算功能。
类图:
实例
Operation类
/**
* @Auther: 李景然
* @Date: 2018/12/12 20:34
* @Description: 抽象类
*/
public abstract class Operation {
private double numberA;
private double numberB;
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;
}
//注意这里的throws Exception
public abstract double getResult() throws Exception;
}
OperationAdd类
public class OperationAdd extends Operation {
@Override
public double getResult(){
double result=getNumberA()+getNumberB();
return result;
}
}
OperationMul类
public class OperationMul extends Operation {
@Override
public double getResult(){
double result=getNumberA()*getNumberB();
return result;
}
}
OperationDiv类
public class OperationDiv extends Operation {
@Override
public double getResult() throws Exception {
double result=0;
if(getNumberB()==0)
throw new Exception("除数不能为0!");
result=getNumberA()/getNumberB();
return result;
}
}
OperationFactory类
public class OperationFactory {
public static Operation createOperation(String operate){
Operation obj=null;
switch (operate){
case "+":
obj=new OperationAdd();
break;
case "-":
obj=new OperationSub();
break;
case "*":
obj=new OperationMul();
break;
case "/":
obj=new OperationDiv();
break;
}
return obj;
}
}
Main客户端类
public class Main {
public static void main(String[] args) throws Exception {
Operation obj=OperationFactory.createOperation("/");
obj.setNumberA(10);
obj.setNumberB(0);
System.out.println(obj.getResult());
}
}
参考:
程杰. 《大话设计模式》