【设计模式】简单工厂模式
程序员文章站
2022-03-09 21:44:33
目的是为了可维护、可复用、可扩展、灵活性好 以四则运算为例: 先有个父类运算类: ......
目的是为了可维护、可复用、可扩展、灵活性好
以四则运算为例:
先有个父类运算类:
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;
}
}
}