码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式2---工厂模式

时间:2014-11-26 16:19:57      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   ar   color   os   sp   for   

为了解决简单工厂模式的缺点,我们通过接口IFactory抽象出工厂类,然后每次增加一个操作类,我就增加工厂类,

从而达到:对扩展开放,对修改关闭。

还是计算器的问题:

UML如下:

bubuko.com,布布扣

 

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---工厂模式

标签:des   style   blog   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/deman/p/4123250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!