策略模式的概念圖
策略模式源來
在生活中述召,實現(xiàn)一個目標有多種方式方法蟹地,也就是有多種策略积暖」钟耄可以用if-else來簡單的判斷,但是當條件變多分别,并且條件變復雜后遍愿,耦合會十分的高,邏輯混亂不夠清晰沼填。
所以就產生了策略模式括授。
首先有一個上下文類Context荚虚,這個類持有一個策略的類引用 Strategy,并且有一個set方法梯澜。
public Class Context{
Strategy strategy;
public void Context(Strategy strategy){
this.strategy=strategy;
}
public void doSomething(){
strategy.doSomething();
}
}
然后將Strategy當做接口類腊徙,聲明必須要實現(xiàn)的方法doSomething(),實現(xiàn)它的多個策略子類螟蝙。
public inteface Strategy{
public void doSomething();
}
public Class OneStrategy implement Strategy{
public void doSomething(){
System.out.println("one");
}
}
public Class TwoStrategy implement Strategy{
public void doSomething(){
System.out.println("two");
}
}
最后使用策略OneStrategy來解決問題胰默。
public void main(){
Context context=new Context(new OneStrategy);
context.doSomething();
}
若要是用策略TwoStrategy漓踢,將TwoStrategy 傳遞進Context中即可喧半。
核心思路是,持有接口引用取具,使用實現(xiàn)接口的具體類來覆蓋其方法扁耐,可擴展性和維護性極強婉称。