【設計模式】簡單工廠模式

bongo發表於2018-07-23

目的是為了可維護、可複用、可擴充套件、靈活性好

以四則運算為例:

先有個父類運算類:

  

public class Operation {
    protected double numberA = 0;
    protected double numberB = 0;

    public double getResult(); 
}    

然後由子類繼承

class OperateAdd extends Operation{
  public double getResult() {
    double result = 0;
    return numberA + numberB;
}
}
class OperateSub extends Operation {
public double getResult() {
    double result = 0;
    return numberA - numberB;
}
最後再是工廠類
public class OperationFactory {
  public static Operation createOperate(String operate) {
    Operation op = null;
    switch(operate) {
      case "+":
      op = new OperationAdd;
      case "-":
      op = new OperationSub;

}

    return op;
}
}
}

相關文章