策略模式學習筆記--在寫更好的代碼路上

策略模式:將算法封裝到類中,針對不一樣的場景,提供不一樣的算法。主要成員:Context(算法接收者) Strategy(算法接口) StrategyImpl(算法是實現者)算法

優勢:靈活切換不一樣算法,減小If語句的使用設計模式

缺點:策略過多致使策略類膨脹測試

舉個例子:this

根據條件運算輸入參數的加法或者減法spa

算法接口設計

package strategy;

/**
 * @author ZHONGZHENG664
 * @date 2018/7/15.
 */
public interface Strategy {
    /**
     * 針對a和b的運算
     * @param a
     * @param b
     * @return
     */
    int doSomething(int a,int b);
}

 

算法使用環境code

package strategy;

/**
 * @author ZHONGZHENG664
 * @date 2018/7/15.
 */
public class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public int execute(int a,int b){
        return this.strategy.doSomething(a, b);
    }
}

 

加法算法的實現:blog

package strategy;

/**
 * @author ZHONGZHENG664
 * @date 2018/7/15.
 */
public class AddStrategy implements Strategy {

    public int doSomething(int a, int b) {
        return a+b;
    }
}

減法算法的實現:接口

package strategy;

/**
 * @author ZHONGZHENG664
 * @date 2018/7/15.
 */
public class SubStrategy implements Strategy {

    public int doSomething(int a, int b) {
        return a-b;
    }
}

測試實現:class

package strategy;

/**
 * @author ZHONGZHENG664
 * @date 2018/7/15.
 */
public class Test {
    public static void main(String[] ags){
        System.out.println("hrll");
        Context context=new Context(new SubStrategy());
        System.out.println("10-5="+context.execute(10,5));
        context=new Context(new AddStrategy());
        System.out.println("10+5="+context.execute(10,5));
    }
}

 

總結:

  策略模式是一個比較簡單的設計模式,在平常使用時咱們也會把比較大的代碼塊放到一個方法中,而後根據if進行判斷調用,已經很相似策略模式了。策略模式須要調用者知道那種「場景」調用何種「策略」,仍是有提高空間的,能夠考慮結合工廠模式進行。

 

基礎模式是設計複雜場景的基礎!從基礎作起,在路上就好!

相關文章
相關標籤/搜索