策略模式-Java

     策略模式的功能是把具體的算法實現,從具體的業務處理裏面獨立出來,把它們實現成爲單獨的算法類,

從而造成一系列的算法,並讓這些算法能夠相互替換。java

     策略模式的重心不是如何來實現算法,而是如何組織、調用這些算法,從而讓程序結構更靈活、具備更好

的維護性和擴展性。算法

     優勢: 1避免多重條件語句。this

                2,更好的擴展性(增長新的實現類)。
spa

     缺點: 1,客戶端必須知道全部的策略類。code

                2,增長了對象數目。對象


來個簡單的例子:接口

/**
 * 1.對策略對象定義一個公共接口。
 * 2.編寫策略類,該類實現了上面的公共接口。
 * 3.在使用策略對象的類中保存一個對策略對象的引用。
 * 4.在使用策略對象的類中,實現對策略對象的set和get方法。
 */

class StrategyExample {
 
    public static void main(String[] args) {
 
        Context context;
 
        context.setStrategy(new FirstStrategy());
        context.execute();
 
        context.setStrategy(new SecondStrategy());
        context.execute();
 
        context.setStrategy(new ThirdStrategy());
        context.execute();
    }
 
}

//定義策略接口
interface Strategy {
 
    void execute();
}

//定義策略實現類
class FirstStrategy implements Strategy {
 
    public void execute() {
        System.out.println("Called FirstStrategy.execute()");
    }
 
}

//定義策略實現類
class SecondStrategy implements Strategy {
 
    public void execute() {
        System.out.println("Called SecondStrategy.execute()");
    }
}
//定義策略實現類 
class ThirdStrategy implements Strategy {
 
    public void execute() {
        System.out.println("Called ThirdStrategy.execute()");
    } 
}

//定義使用策略的上下文 
class Context {
 
    Strategy strategy;
 
    public Context(Strategy strategy)
    {
        this.strategy = strategy;
    }

    public void setStrategy(Strategy strategy)
    {
        this.strategy = strategy;
    }

    public Strategy getStrategy()
    {
        return this.strategy;
    }
 
    public void execute() {
        this.strategy.execute();
    }
}
相關文章
相關標籤/搜索