定義
將一系列相關(guān)的算法中的每一個都封裝起來,并使它們可以相互替換,即使算法可以獨立于調(diào)用者。
使用場景
(1)針對同一類型的問題的多種處理方式僅是具體行為有差別時
(2)需要安全地封裝多種同一類型的操作時
(3)出現(xiàn)同一抽象類有多個子類,而又需要使用if-else或者switch-case來選擇具體子類時
UML類圖

實現(xiàn)方式(省略Director類和抽象的Buidler父類)
Stragety接口
public interface Stragety{
? ? int algorithm();
}
Stragety類A
public class StragetyA implements Stragety{
? ? @Override
? ? public int algorithm(){
? ? ? ? return 1;
? ? }
}
Stragety類B
public class StragetyB implements Stragety{
? ? @Override
? ? public int algorithm(){
? ? ? ? return 2;
? ? }
}
Context類:
public class Context{
? ? Stragety mStragety;
? ? public void setStragety(Stragety stragety){
? ? ? ? this.mStragety = stragety
? ? }
? ? public int algorithm(){
? ? ? ? return mStragety.algorithm();
? ? }
}
調(diào)用例子:
public void class Test{
? ? public staticvoid main(String [] args){
? ? ? ??StragetyA a = new StragetyA();
? ? ? ? Context context = new Context();
? ? ? ? context.setStragety(a);
? ? ? ? context.algorithm();
? ? }
}
策略模式的優(yōu)缺點
優(yōu)點
>結(jié)構(gòu)清晰明了,使用簡單直觀
>耦合度相對而言較低,擴展方便
>操作封裝較為徹底,數(shù)據(jù)對外封閉,更安全
缺點
>隨著策略的增加,子類會變得繁多
Android中的策略模式舉例
TimeInterpolator,時間插值器,在動畫中使用
——2017.08.08