Strategy
概念
策略模式:Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. 定义一族算法类,将每个算法分别封装起来,让它们可以互相替换。策略模式可以使算法的变化独立于使用它们的客户端。
策略模式用于解耦策略的定义、创建、使用三部分。
常见的应用场景是避免冗长的 if-else 或 switch 分支判断。也能像模板方法一样,提供框架扩展点。
示例
定义
public interface Strategy {
void algorithmInterface();
}
public class ConcreteStrategyA implements Strategy {
@Override
public void algorithmInterface() {
//具体的算法...
}
}
public class ConcreteStrategyB implements Strategy {
...
}创建
使用
Last updated
Was this helpful?
