samson

 

设计模式——简单工厂模式

工作之后,一直忙于工作,像一位前辈所说的那样,我的确需要好好总结一下所学所用过的知识了。

就从复习设计模式开始,今天复习的是简单工厂设计模式。

如设计一个简单的计算器程序:

  需要从Console端获得两个数字、一个运算符(+-*/),并计算得出结果。

  

此处可利用简单工厂根据运算符生成运算类,类图如下:

package sf.simpleFactory;

import sf.simpleFactory.Operator.DivisionOperator;
import sf.simpleFactory.Operator.MinusOperator;
import sf.simpleFactory.Operator.MultipleOperator;
import sf.simpleFactory.Operator.PlusOperator;

public class OperatorFactory {
    public static Operator getInstance(int digit1, int digit2, String operator) {
        if (operator.equals("+")) {
            return new PlusOperator(digit1, digit2, operator);
        } else if (operator.equals("-")) {
            return new MinusOperator(digit1, digit2, operator);
        } else if (operator.equals("*")) {
            return new MultipleOperator(digit1, digit2, operator);
        } else if (operator.equals("/")) {
            return new DivisionOperator(digit1, digit2, operator);
        } else {
            return null;
        }
    }
}
package sf.simpleFactory;

public abstract class Operator {
    public int digit1;
    public int digit2;
    public Operator(int digit1, int digit2, String operator) {
        this.digit1 = digit1;
        this.digit2 = digit2;
    }
    public abstract float calculate();

    public static class PlusOperator extends Operator{
        public PlusOperator(int digit1, int digit2, String operator) {
            super(digit1, digit2, operator);
        }
        @Override
        public float calculate() {
            return digit1 + digit2;
        }
    }
    
    public static class MinusOperator extends Operator{
        public MinusOperator(int digit1, int digit2, String operator) {
            super(digit1, digit2, operator);
        }
        @Override
        public float calculate() {
            return digit1 - digit2;
        }
    }
    
    public static class MultipleOperator extends Operator{
        public MultipleOperator(int digit1, int digit2, String operator) {
            super(digit1, digit2, operator);
        }
        @Override
        public float calculate() {
            return digit1 * digit2;
        }
    }
    
    public static class DivisionOperator extends Operator{
        public DivisionOperator(int digit1, int digit2, String operator) {
            super(digit1, digit2, operator);
        }
        @Override
        public float calculate() {
            return digit1 / digit2;
        }
    }
}

 

 

posted on 2014-02-10 22:50  samson  阅读(285)  评论(0编辑  收藏  举报

导航