策略模式
一个类的行为或其算法可以在运行时更改。
一个接口calculate进行规范
然后add,subtraction 都继承该接口,实现自己特定的行为。
/**
* Created by malei on 2016/12/6.
*/
public class Computer {
private final Calculate calculate;
public Computer(Calculate calculate){
this.calculate = calculate;
}
public int exe(int a, int b){
return calculate.operate(a,b);
}
public static void main(String[] args){
Computer add = new Computer(new AddOperate());
Computer sub = new Computer(new SubtraOperate());
Log.show(add.exe(1,1));
Log.show(sub.exe(1,1));
}
}
/**
* Created by malei on 2016/12/6.
* 相加操作
*/
public class AddOperate implements Calculate{
@Override
public int operate(int a, int b) {
return a+b;
}
}
/**
* Created by malei on 2016/12/6.
*/
public class SubtraOperate implements Calculate{
@Override
public int operate(int a, int b) {
return a-b;
}
}
/**
* Created by malei on 2016/12/6.
* 数学计算接口规范
*/
public interface Calculate {
int operate(int a,int b);
}