策略模式的概念圖
策略模式源來
在生活中,實現一個目標有多種方式方法,也就是有多種策略。可以用if-else來簡單的判斷,但是當條件變多,并且條件變復雜后,耦合會十分的高,邏輯混亂不夠清晰。
所以就產生了策略模式。
首先有一個上下文類Context,這個類持有一個策略的類引用 Strategy,并且有一個set方法。
public Class Context{
Strategy strategy;
public void Context(Strategy strategy){
this.strategy=strategy;
}
public void doSomething(){
strategy.doSomething();
}
}
然后將Strategy當做接口類,聲明必須要實現的方法doSomething(),實現它的多個策略子類。
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中即可。
核心思路是,持有接口引用,使用實現接口的具體類來覆蓋其方法,可擴展性和維護性極強。