文章出處

使用頻率:★★★★☆

什么是策略模式

對象的行為,在不同的環境下,有不同的實現;

比如人的上班行為,在不同的環境下,可以選擇走路上班或者開車上班,由客戶端根據情況決定采用何種策略;

補充說明

符合“開閉原則”,可以在不修改原有代碼的基礎上替換、添加新的策略;

不同的策略可以相互替換;

客戶端自己決定在什么情況下使用什么具體策略角色;

與狀態模式區別:使用策略模式時,客戶端手動選擇策略,使用狀態模式時,其行為是根據狀態是自動切換的。

角色

抽象策略

具體策略

環境

例子,JAVA實現

例子描述:人上班,使用步行或者開車上班;

策略:步行上班、開車上班...

關系圖

抽象策略接口

package com.pichen.dp.behavioralpattern.strategy;

public interface IStrategy {

    public void execute();
}

具體策略

package com.pichen.dp.behavioralpattern.strategy;

public class DriveStrategy implements IStrategy{

    /**
     * @see com.pichen.dp.behavioralpattern.strategy.IStrategy#execute()
     */
    @Override
    public void execute() {
        System.out.println("driving。。。");
    }

}
package com.pichen.dp.behavioralpattern.strategy;

public class WalkStrategy implements IStrategy{

    /**
     * @see com.pichen.dp.behavioralpattern.strategy.IStrategy#execute()
     */
    @Override
    public void execute() {
        System.out.println("walking。。。");
    }

}

環境

package com.pichen.dp.behavioralpattern.strategy;

public class Context {

    IStrategy strategy;
    
    public Context(IStrategy strategy) {
        this.strategy = strategy;
    }
    
    public void execute() {
        this.strategy.execute();
    }
}

客戶端

package com.pichen.dp.behavioralpattern.strategy;

public class Main {
    public static void main(String[] args) {
        Context context = null;
        context = new Context(new WalkStrategy());
        context.execute();
        context = new Context(new DriveStrategy());
        context.execute();
    }
}

結果打印

walking。。。
driving。。。

 JDK中的示例,Collections.sort方法

不需為新的對象修改sort()方法,你需要做的僅僅是實現你自己的Comparator接口:

        Collections.sort(
            list,   //待排序的集合
            new Comparator<>(){  //具體排序策略
            @Override  
            public int compare(A a1, A a2) {  
                return ; //具體大小判斷規則 
            }  
        });  

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()