策略模式实践
举例用策略模式实现加减运算,首先定义抽象策略角色(Strategy接口)
public interface IStrategy {
int exec(int a, int b);
}
然后定义加减法具体策略角色(ConcreteStrategyA,ConcreteStrategyB)
public class StrategyADD implements IStrategy {
@Override
public int exec(int a, int b) {
return a + b;
}
}
public class StrategySub implements IStrategy {
@Override
public int exec(int a, int b) {
return a - b;
}
}
定义封装角色(Context)
public class Calculator {
private IStrategy strategy;
public Calculator(IStrategy strategy) {
this.strategy = strategy;
}
public int exec(int a, int b) {
return strategy.exec(a, b);
}
}
测试
@Test
public void testStrate() {
IStrategy strategy = new StrategyADD();
int result = new Calculator(strategy).exec(1, 3);
IStrategy strategy2 = new StrategySub();
int result2 = new Calculator(strategy2).exec(2, 1);
assertEquals(4, result);
assertEquals(1, result2);
}
策略枚举
Effective Java 第二版的第30条就给出来策略枚举模式,运用策略枚举来实现上面的策略模式
public enum CalculatorEnum {
ADD("+") {
@Override
public int exec(int a, int b) {
return a + b;
}
},
SUB("-") {
@Override
public int exec(int a, int b) {
return a - b;
}
};
CalculatorEnum(String s) {
this.value = s;
}
private final String value;
public abstract int exec(int a, int b);
}
测试
@Test
public void testCalculatorEnum() {
int addResult = CalculatorEnum.ADD.exec(1, 3);
int subResult = CalculatorEnum.SUB.exec(2, 1);
assertEquals(4, addResult);
assertEquals(1, subResult);
}
总之,每当需要一组固定常量的时候,就应该使用枚举。多个枚举常量同时共享相同的行为用策略枚举。
网友评论