策略模式——《設計模式之禪》
很好理解的例子
劉備江東娶親,三個錦囊妙計
一個接口,三個實現類,三個錦囊妙計
interface IStrategy{
public void operate();
}
/**
* 錦囊妙計1:找喬國老幫忙說情,娶了孫尚香
*/
public class BackDoor implements IStrategy{
public void operate{
System.out.println("找喬國老幫忙說情,娶孫尚香");
}
}
/**
* 錦囊妙計2:找吳國太哭訴,企圖給自己開綠燈,方便逃走
*/
public class GivenGreenLight implements IStrategy{
public void operate{
System.out.println("找吳國太哭訴,企圖給自己開綠燈,方便逃走");
}
}
/**
* 錦囊妙計3:孫尚香死守,力求斷后
*/
public class BlockEnemy implements IStrategy{
public void operate{
System.out.println("孫尚香死守,力求斷后");
}
}
封裝類,Contex也就是錦囊,承載3個妙計
/**
* 封裝類,Contex也就是錦囊,承載3個妙計
*/
public class Context{
private IStrategy strategy;
public Context(IStrategy strategy){
this.strategy = strategy;
}
public void operate(){
this.strategy.operate();
}
}
使用計謀
public class ZhaoYun{
public static void main(String[] args) {
Context context;
system.out.println("剛剛到吳國的時候,打開第一條錦囊妙計");
context = new Context(new BackDoor());
context.operate();
system.out.println("樂不思蜀,打開第二條錦囊妙計");
context = new Context(new GivenGreenLight());
context.operate();
system.out.println("追兵來了");
context = new Context(new BlockEnemy());
context.operate();
}
}
策略模式總結
Define a family of algorithms, encapsulate each other, and make them interchangeable.
定義一組算法,將每個算法都封裝起來,并且使它們之間可以互換
策略模式
- Context封裝角色
上下文角色,起到承上啟下封裝作用,屏蔽高層模塊對策略、算法的直接訪問、封裝可能存在的變化
public class Context {
private Strategy strategy = null;
public Context(Strategy strategy){
this.strategy = strategy;
}
public void doSomething(){
this.strategy.doSomething();
}
}
- Strategy抽象策略角色
策略、算法家族的抽象,通常為接口,定義每個策略或算法必須具有的方法和屬性
public interface Strategy{
public void doSomething();
}
- ConcreteStrategy 具體策略角色
實現抽象策略中的操作,該類含有具體的算法
public class ConcreteStrategy implements Strategy {
public void doSomething(){
//code to do something
}
}
class ConcreteStrategy2 implements Strategy {
public void doSomething(){
//code to do something
}
}
- 高層調用Client
public class Client {
public static void main(String[] args) {
Strategy strategy = new ConcreteStrategy();
Context context = new Context(strategy);
context.doSomething();
}
}
策略模式優點
- 算法可以自由切換
- 避免使用多重條件判斷
- 擴展性良好
策略模式缺點
- 策略類數量增多
- 所有的策略類都必須對外暴露
策略模式的使用場景
- 多個類只有在算法或行為上稍有不同的場景
- 算法需要自由切換的場景
- 需要屏蔽算法規則的場景