简单工厂模式严格意义上不是一种设计模式,它是工厂设计模式的一个特殊实现,又称为静态工厂方法模式,说白了就是由一个工厂对象决定创建出哪一种产品类的实例。一个是工厂类Creator负责生产产品的逻辑判断,一个是产品接口(或者抽象类)IProduct定义了产品通用的属性/操作,为了使工厂类能够知道我们需要哪一种产品,我们需要在创建产品时传递给工厂类一个参数,去表明我们想要创建哪种产品。下面是范例:
举个栗子,如果我们想写一个计算器,首先写出了加法运算,然后又想写一个减法......这么多运算如果扩展起来维护肯定捉襟见肘。所以我们考虑,这些都是运算,我定义一个抽象类Operation,里面直接返回运算的结果,具体如何实现的由实现它的子类具体实现,然后定义一个生产运算的工厂,当需要什么运算给工厂发送个信号生产出相应的运算。这样如果新的运算扩展只需要继承“运算”类,自己该怎么实现就怎么实现,各个运算间互不影响,维护起来也方便。
运算抽象类Operation
package com.zndroid.dm.FactoryModel.EasyFactory;
/**
* Created by luzhenyu on 2016/8/15.
*/
public abstract class Operation {
protected double numA;
protected double numB;
public void setNumA(double numA) {
this.numA = numA;
}
public void setNumB(double numB) {
this.numB = numB;
}
public abstract double getResult();
}
具体运算实现
package com.zndroid.dm.FactoryModel.EasyFactory.impl;
import com.zndroid.dm.FactoryModel.EasyFactory.Operation;
/**
* Created by luzhenyu on 2016/8/15.
*/
public class AddOperator extends Operation {
@Override
public double getResult() {
return numA + numB;
}
}
package com.zndroid.dm.FactoryModel.EasyFactory.impl;
import com.zndroid.dm.FactoryModel.EasyFactory.Operation;
/**
* Created by luzhenyu on 2016/8/15.
*/
public class DivisionOperator extends Operation {
@Override
public double getResult() {
return numA / numB;
}
}
运算工厂Factory
package com.zndroid.dm.FactoryModel.EasyFactory;
import com.zndroid.dm.FactoryModel.EasyFactory.impl.AddOperator;
import com.zndroid.dm.FactoryModel.EasyFactory.impl.DivisionOperator;
/**
* Created by luzhenyu on 2016/8/13.
*/
public class Easyfactory {
public static Operation createOperation (String operator) {
Operation mOpration = null;
if ("".equals(operator) || null == operator)
return null;
switch (operator){
case "+":
mOpration = new AddOperator();
break;
case "/":
mOpration = new DivisionOperator();
break;
}
return mOpration;
}
}
使用:
package com.lzy.zndroid;
import com.zndroid.dm.FactoryModel.EasyFactory.Easyfactory;
import com.zndroid.dm.FactoryModel.EasyFactory.Operation;
import com.zndroid.dm.SingletonModel.SingletonModel;
public class Demo {
public static void main(String[] args){
log("========================================");
SingletonModel s1 = SingletonModel.getInstance();
SingletonModel s2 = SingletonModel.getInstance();
log("" + (s1 == s2));
log("----------------我是分割线-----------------");
Operation addOperator = Easyfactory.createOperation("+");
addOperator.setNumA(100);
addOperator.setNumB(150);
log(addOperator.getResult() + "");
Operation divisionOperator = Easyfactory.createOperation("/");
divisionOperator.setNumA(888);
divisionOperator.setNumB(4);
//Demo暂时不考虑被除数为“0”的情况
log(divisionOperator.getResult() + "");
log("----------------我是分割线-----------------");
log("========================================");
}
private static void log(String msg) {
System.out.println("[ " + msg + " ]");
}
}
总闻到一点不好的味道,代码出现在哪里呢?
【欢迎上码】
【微信公众号搜索 h2o2s2】