62,614
社区成员
发帖
与我相关
我的任务
分享
public interface Strategy { //策略
public int calculate(int a,int b);
}
这是一个接口,它里面只有方法,没有具体的实现。
你必须先调用setXXX(),才能给变量赋值,否则怎么能用呢?
不过你的加减乘除何不放在一个类里面做成4个方法?看起来也方便,也利于后期的维护。
package com.strategytest;
public class Environment { // 环境角色
private Strategy strategy;
public Environment(Strategy strategy) {
// TODO Auto-generated constructor stub
this.strategy = strategy;
}
public Strategy getStrategy() {
return strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public int calculate(int a,int b) {
return strategy.calculate(a, b);
}
}
public interface Strategy { //策略
public int calculate(int a,int b);
}
public class AddStrategy implements Strategy { //加法策略
@Override
public int calculate(int a,int b) {
// TODO Auto-generated method stub
return a + b;
}
}
public class SubstractStrategy implements Strategy { //减法策略
@Override
public int calculate(int a, int b) {
// TODO Auto-generated method stub
return a - b;
}
}
public class MultiplyStrategy implements Strategy { //乘法策略
@Override
public int calculate(int a, int b) {
// TODO Auto-generated method stub
return a * b;
}
}
public class DivideStrategy implements Strategy { //除非策略
@Override
public int calculate(int a, int b) {
// TODO Auto-generated method stub
return a / b;
}
}
看看代码