设计模式2---工厂模式
为了解决简单工厂模式的缺点,我们通过接口IFactory抽象出工厂类,然后每次增加一个操作类,我就增加工厂类,
从而达到:对扩展开放,对修改关闭。
还是计算器的问题:
UML如下:
factory 基类:
public interface IOperatorFactory { AbstractOperator CreateOperation(); }
工厂类:
package com.jayfulmath.designpattern.factory; import com.jayfulmath.designpattern.samplefactory.operator.AbstractOperator; import com.jayfulmath.designpattern.samplefactory.operator.OperatorAdd; public class AddFactory implements IOperatorFactory { @Override public AbstractOperator CreateOperation() { // TODO Auto-generated method stub return new OperatorAdd(); } }
package com.jayfulmath.designpattern.factory; import com.jayfulmath.designpattern.samplefactory.operator.AbstractOperator; import com.jayfulmath.designpattern.samplefactory.operator.OperatorPlus; public class PlusFactory implements IOperatorFactory { @Override public AbstractOperator CreateOperation() { // TODO Auto-generated method stub return new OperatorPlus(); } }
main:
package com.jayfulmath.designpattern.factory; import com.jayfulmath.designpattern.main.BasicExample; import com.jayfulmath.designpattern.samplefactory.operator.AbstractOperator; public class FactoryMain extends BasicExample { @Override public void startDemo() { // TODO Auto-generated method stub IOperatorFactory addFactory = new AddFactory(); AbstractOperator addOperation = addFactory.CreateOperation(); addOperation.NumberA = 1; addOperation.NumberB = 2; System.out.println("[FactoryMain]"+addOperation.NumberA+" add "+addOperation.NumberB+" = "+addOperation.GetResult()); } }
工厂接口生成操作基类。
posted on 2014-11-26 15:18 Joyfulmath 阅读(209) 评论(0) 编辑 收藏 举报