软件构造-Strategy 策略模式
Strategy 策略模式
在软件构造的多个实验中,都用到了Strategy 策略模式。
策略模式属于对象的行为模式。其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。
实例结构
这个模式涉及到三个角色:
● 环境(Context)角色:持有一个Strategy的引用。
● 抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。
● 具体策略(ConcreteStrategy)角色:包装了相关的算法或行为。
策略模式上下文
public class Context {
//持有一个具体策略的对象
private Strategy strategy;
/**
* 构造函数,传入一个具体策略对象
* @param strategy 具体策略对象
*/
public Context(Strategy strategy){
this.strategy = strategy;
}
/**
* 策略方法
*/
public void contextInterface(){
strategy.algorithmInterface();
}
}
抽象策略类
public interface Strategy {
/**
* 策略方法
*/
public void algorithmInterface();
}
具体策略类
public class ConcreteStrategyA implements Strategy {
@Override
public void algorithmInterface() {
//相关的业务
}
}
public class ConcreteStrategyB implements Strategy {
@Override
public void algorithmInterface() {
//相关的业务
}
}
public class ConcreteStrategyC implements Strategy {
@Override
public void algorithmInterface() {
//相关的业务
}
}
客户端
//选择使用的策略
Strategy s = new ConcreteStrategyA();
Context context = new Context(s);
context.ontextInterface();
分析
策略模式的优点:
1算法可以自由切换;
2 避免使用多重条件判断;
3 扩展性良好。
策略模式的缺点:
1策略类会增多
2所有策略类都需要对外暴露
策略模式的适用场景:
1 当一个系统中有许多类,它们之间的区别仅在于它们的行为,希望动态地让一个对象在许多行为中选择一种行为时;
2当一个系统需要动态地在几种算法中选择一种时;
3 当一个对象有很多的行为,不想使用多重的条件选择语句来选择使用哪个行为时。