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

设计模式--工厂模式

时间:2019-10-11 23:07:11      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:case   his   rri   cep   default   except   str   row   计算   

还是以计算器为例

首先定义Operation接口和Add,Sub,Mul,Div操作

public interface Operation {
  public double getResult(double a, double b);
}

public class Add implements Operation {

  @Override
  public double getResult(double a, double b) {
    return a + b;
  }

}

public class Sub implements Operation {

  @Override
  public double getResult(double a, double b) {
    return a - b;
  }

}

public class Mul implements Operation {

  @Override
  public double getResult(double a, double b) {
    return a * b;
  }

}

public class Div implements Operation {

  @Override
  public double getResult(double a, double b) {
    if (b == 0) {
      throw new IllegalArgumentException("除数不能为0!");
    }
    return a / b;
  }

}

接下来创建工厂类

public class OperationFactory {
  public static Operation ceateOperation(String op) {
    Operation operation = null;
    switch (op) {
      case "+":
        operation = new Add();
        break;
      case "-":
        operation = new Add();
        break;
      case "*":
        operation = new Add();
        break;
      case "/":
        operation = new Add();
        break;
      default:
        break;
    }
    return operation;
  }
}

改善一下,使用枚举工厂

public enum OperationEnmu {
  ADD, MUL, DIV, SUB;
  public Operation createOperation() {
    Operation operation = null;
    switch (this) {
      case ADD:
        operation = new Add();
        break;
      case MUL:
        operation = new Mul();
        break;
      case DIV:
        operation = new Div();
        break;
      case SUB:
        operation = new Sub();
        break;
      default:
        break;
    }
    return operation;
  }
}

 

--后面更新抽象工厂

 

设计模式--工厂模式

标签:case   his   rri   cep   default   except   str   row   计算   

原文地址:https://www.cnblogs.com/lz-0011/p/11657532.html

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