欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

工厂模式--简单工厂模式

程序员文章站 2024-01-20 16:48:10
...

简单说说简单工厂模式:

需求:设计个计算器,两个数字之间的加减乘除基本运算。

首先是Operation运算抽象类:

package com.SimpleFactory;

/**
 * 简单工厂模式
 * @Description: 运算抽象类
 * @Date 2018/7/25
 */
public abstract class Operation {
    public double number1;
    public double number2;

    public double getNumber1() {
        return number1;
    }

    public void setNumber1(double number1) {
        this.number1 = number1;
    }

    public double getNumber2() {
        return number2;
    }

    public void setNumber2(double bumber2) {
        this.number2 = bumber2;
    }

    public abstract double getResult() throws Exception;
}

 

继承Operation的加法类:OperationAdd加法运算类

package com.SimpleFactory;

/**
 * 简单工厂模式
 * @Description: 加法
 * @Date 2018/7/25
 */
public class OperationAdd extends Operation {
    @Override
    public double getResult() {
        return number1 + number2;
    }
}

继承Operation的减法类:OperationSub减法运算类

package com.SimpleFactory;

/**
 * 简单工厂模式
 * @Description: 减法
 * @Date 2018/7/25
 */
public class OperationSub extends Operation {
    @Override
    public double getResult() {
        return number1 - number2;
    }
}

继承Operation的乘法类:OperationMul乘法运算类

package com.SimpleFactory;

/**
 * 简单工厂模式
 * @Description: 乘法
 * @Date 2018/7/25
 */
public class OperationMul extends Operation {
    @Override
    public double getResult() {
        return number1 * number2;
    }
}

继承Operation的除法类:OperationDiv除法运算类

package com.SimpleFactory;

/**
 * 简单工厂模式
 * @Description: 除法
 * @Date 2018/7/25
 */

public class OperationDiv extends Operation {
  @Override
    public double getResult() throws Exception {
      if (number2 == 0){
          throw new Exception("除数不能为0");
      }
      return number1/number2;
  }
}

生成Operation的工厂类:OperationFactory

package com.SimpleFactory;

/**
 * 简单工厂模式
 * @Description: 生成Operation的工厂类
 * @Date 2018/7/25
 */
public class OperationFactory {
    public static Operation createOperation(char operation) {
        Operation oper = null;
        switch (operation) {
            case '+':
                oper =new OperationAdd();
                break;
            case '-':
                oper =new OperationSub();
                break;
            case '*':
                oper =new OperationMul();
                break;
            case '/':
                oper =new OperationDiv();
                break;
            default:
                break;
        }
        return oper;
    }
}

测试类:

package com.SimpleFactory;

/**
 * 简单工厂模式
 * @Description: 测试简单工厂模式
 * @Date 2018/7/25
 */
public class Test {
    public static void main(String[] args) {
        Operation oper;
        oper = OperationFactory.createOperation('/');
        oper.number1 = 1;
        oper.number2 = 2;
        try {
            System.out.println(oper.getResult());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}