设计模式--工厂模式

还是以计算器为例

首先定义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;
  }
}

 

--后面更新抽象工厂

 

上一篇:第80天:Python-Operation_MySQL


下一篇:大话设计模式------简单工厂模式