父類
public abstract class Operator {
private double d1;
private double d2;
public double getD1() {
return d1;
}
public void setD1(double d1) {
this.d1 = d1;
}
public double getD2() {
return d2;
}
public void setD2(double d2) {
this.d2 = d2;
}
public abstract double getResult();
}
加法類
public class OperatorAdd extends Operator{
@Override
public double getResult() {
return this.getD1() + this.getD2();
}
}
減法類
public class OperatorSub extends Operator{
@Override
public double getResult() {
return this.getD1() - this.getD2();
}
}
乘法類
public class OperatorMul extends Operator{
@Override
public double getResult() {
return this.getD1() * this.getD2();
}
}
除法類
public class OperatorDiv extends Operator{
@Override
public double getResult() {
return this.getD1() / this.getD2();
}
}
策略模式
public class OperatorContext {
private Operator operator;
public OperatorContext(String type){
switch (type){
case "+":
this.operator = new OperatorAdd();
break;
case "-":
this.operator = new OperatorSub();
break;
case "*":
this.operator = new OperatorMul();
break;
case "/":
this.operator = new OperatorDiv();
break;
default:
break;
}
}
public double getResult(double d1,double d2){
this.operator.setD1(d1);
this.operator.setD2(d2);
return this.operator.getResult();
}
}
使用
public static void main(String[] args) {
OperatorContext context = new OperatorContext("+");
double res = context.getResult(123,111);
System.out.println(res);
}
輸出
234.0