每天分享java干货知识,欢迎关注转发评论交流,每天一点进步!
什么是策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
策略模式应用场景策略模式的用意是针对一组算法或逻辑,将每一个算法或逻辑封装到具有共同界面的独立的类中,从而使得它们之间可以相互替换。策略模式使得算法或逻辑可以在不影响到客户端的情况下发生变化。说到策略模式就不得不提及OCP(Open Closed Principle) 开闭原则,即对扩充套件开放,对修改关闭。策略模式的出现很好地诠释了开闭原则,有效地减少了分支语句。
程式码如下:package com.pzx.designmodle.strategy;
//策略模式 定义抽象方法 所有支援公共界面
abstract class Strategy {
// 算法方法
abstract void algorithmInterface();
}
class StrategyA extends Strategy {
@Override
void algorithmInterface() {
System.out.println("算法A");
}
}
class StrategyB extends Strategy {
@Override
void algorithmInterface() {
System.out.println("算法B");
}
}
class StrategyC extends Strategy {
@Override
void algorithmInterface() {
System.out.println("算法C");
}
}
// 使用上下文维护算法策略
class Context {
Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void algorithmInterface() {
strategy.algorithmInterface();
}
}
public class ClientTestStrategy {
public static void main(String[] args) {
Context context;
context = new Context(new StrategyA());
context.algorithmInterface();
context = new Context(new StrategyB());
context.algorithmInterface();
context = new Context(new StrategyC());
context.algorithmInterface();
}
}