策略模式實踐
舉例用策略模式實現(xiàn)加減運算族展,首先定義抽象策略角色(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條就給出來策略枚舉模式,運用策略枚舉來實現(xiàn)上面的策略模式
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);
}
總之,每當需要一組固定常量的時候,就應(yīng)該使用枚舉汛骂。多個枚舉常量同時共享相同的行為用策略枚舉。
參考文章
策略模式(政策模式) 策略枚舉
優(yōu)雅編程之這樣使用枚舉和注解评腺,你就“正沉辈t!绷耍ǘ牛?/a>