工厂模式三部曲之工厂方法模式
工厂方法模式有四要素
- 产品接口
- 产品实现
- 工厂接口
- 工厂实现
和简单工厂模式的区别
简单工厂模式只有三个要素,它没有工厂接口,并且得到的产品方法一般是静态的。因为没有工厂接口,所以在工厂实现的扩展性方面较弱,可以算作工厂方法模式的简化版。
计算器的例子用工厂方法模式实现
类图如下:
项目如下:
代码如下:
IFactory:
public interface IFactory { public Operation createOperation(); }
AddFactory:
public class AddFactory implements IFactory { @Override public Operation createOperation() { return new AddOperation(); } }
SubFactory:
public class SubFactory implements IFactory { @Override public Operation createOperation() { return new SubOperation(); } }
MulFactory:
public class MulFactory implements IFactory { @Override public Operation createOperation() { return new MulOperation(); } }
DivFactory:
public class DivFactory implements IFactory { @Override public Operation createOperation() { return new DivOperation(); } }
剩下的类和简单工厂模式的一样。
可以参考:http://www.cnblogs.com/DarrenChan/p/5661356.html
测试:
IFactory fac = new DivFactory(); Operation oper = fac.createOperation(); oper.setNumber1(3.3); oper.setNumber2(5.12); System.out.println(oper.getResult());