## 简单工厂模式 ##
什么是简单工厂模式
** 简单的工厂模式 **:到底要实例谁,将来会不会增加实例化的对象,都应该考虑用一个单独的类来做这个创造实例的过程,这就是工厂。
步骤一
public class OperationObject {
private double _numberA = 0;
private double _numberB = 0;
public double get_numberA() {return _numberA;}
public void set_numberA(double _numberA) {this._numberA = _numberA;}
public double get_numberB() {return _numberB;}
public void set_numberB(double _numberB) {this._numberB = _numberB;}
public double getResult(){
double result = 0;
return result;
}
}
步骤二
// 加法
public class OperationAdd extends OperationObject {public double getResult(){
double result = 0;
result = get_numberA()+get_numberB();
return result;
}
}
// 加法
public class OperationDiv extends OperationObject{public double getResult() {
double result = 0;
if (get_numberB() == 0){
try {throw new Exception("除数不能为零");
} catch (Exception e) {e.printStackTrace();
}
}
result = get_numberA() / get_numberB();
return result;
}
}
// 乘法
public class OperationMul extends OperationObject {public double getResult(){
double result = 0;
result = get_numberA() * get_numberB();
return result;
}
}
// 除法
public class OperationSub extends OperationObject {public double getResult(){
double result = 0;
result = get_numberA() - get_numberB();
return result;
}
}
步骤三
// 简单的工厂模式:到底要实例谁,将来会不会增加实例化的对象,都应该考虑用一个单独的类来做这个创造实例的过程,这就是工厂。// 一句话就是一个工厂里面装着一堆需要实例的对象
public class OperationFactory {public static OperationObject createOperation(String operation){
// 负责生产加减乘除
OperationObject operationObject = null;
switch (operation){
case "+":
operationObject = new OperationAdd();
break;
case "-":
operationObject = new OperationSub();
break;
case "*":
operationObject = new OperationMul();
break;
case "/":
operationObject = new OperationDiv();
break;
}
return operationObject;
}
}
步骤四
public class factoryDesign {public static void main(String[] args) {
// 实例所需要的计算类型
OperationObject operationObject = OperationFactory.createOperation("-");
operationObject.set_numberA(2);
operationObject.set_numberB(4);
double result = operationObject.getResult();
System.out.println(result);
}
}
简单工厂的问题就在于 swich case(或者 if else)。每当新增一种产品时,你都需要去维护工厂中的判断语句,造成该工厂类不断增长,各种判断挤在一起,给扩展和维护带来麻烦。产品和工厂没有实现完全解耦,绑定在一起。
以上内容为个人学习大话设计模式后笔记,不喜勿喷。