首页 > 代码库 > 设计模式2---工厂模式
设计模式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()); }}
工厂接口生成操作基类。
设计模式2---工厂模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。