策略模式

实际案例

一个主题切换案例

1
2
3
public interface Theme {
void applyTheme();
}
1
2
3
4
5
6
public class DefaultTheme implements Theme{
@Override
public void applyTheme() {
System.out.println("设置默认主题");
}
}
1
2
3
4
5
6
public class DarkTheme implements Theme{
@Override
public void applyTheme() {
System.out.println("设置暗黑风格主题");
}
}
1
2
3
4
5
6
public class ColorfulTheme implements Theme{
@Override
public void applyTheme() {
System.out.println("设置彩色风格主题");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class ThemeManager {
private Theme theme;

public ThemeManager() {
this.theme = new DefaultTheme();
}

public void setTheme(Theme theme){
this.theme = theme;
}

public void applyTheme(){
this.theme.applyTheme();
}
}
1
2
3
4
5
6
7
8
public class Client {
public static void main(String[] args) {
ThemeManager themeManager = new ThemeManager();
//设置黑暗风格主题
themeManager.setTheme(new DarkTheme());
themeManager.applyTheme();
}
}

主题模式更换的案例中,不同的主题风格就是一个个策略,我们可以根须需要选择不同的策略。

如何理解策略模式

定义椅子算法,将每个算法都以类的方式凤凰钻起来,并且使他们可以互相交换。

类图(TODO)

策略模式模型抽象

  • Context封装角色

主题更换案例中的ThemeManager就是一个封装角色,也叫上下文角色,拼比高层对策略的直接访问。

  • Strategy抽象策略角色

定义每个策略必须具有的方法和属性

  • ConcreteStrategy具体策略角色

抽象策略的实现,具体的算法

策略模式的优点

  • 算法可以自由切换
  • 避免了多重条件的判断
  • 良好的扩展性(符合开闭原则)

策略模式的缺点

  • 策略类会逐渐增多(超过四个考虑使用混合模式)
  • 策略类必须向外暴露(违反迪米特法则) — 上层模块必须知道哪些策略,才能使用哪些策略,可用工厂方法模式修正

策略模式的具体应用

  • Shiro权限控制框架有三种验证策略