strategyPattern
例子:假设小明有时会超速,他可能被一个很nice 的police抓到,但是会让小明走而且不开bill,只是简单的警告下。
也有可能被一个hard的police抓到,会给他bill。但是小明不知道他会被 什么样的警察抓到,直到他被抓到前。这种就是
run time .这个是strategy设计模式的核心。
设计 一个strategy interface,里面有一个方法。
public interface Strategy { public void processSpeeding (int speed); }
现在我们有两种警察
public class NicePolice implements Strategy{ public void processSpeeding(int speed) { System.out.println("just go") ; } }
另外一个
public class HardPolice implements Strategy{ public void processSpeeding(int speed) { System.out.println("you bill"); } }
设计 一个解决方案,决定 那个警察将会处理事件
public class Solution { private Strategy strategy ; public Solution(Strategy strategy){ this.strategy = strategy ; } public void handleByPolice(int speed){ this.strategy.processSpeeding(speed) ; } }
最后是测试
public class StrategyPattern { public static void main(String [] args ){ HardPolice hPolice = new HardPolice() ; NicePolice nicePolice= new NicePolice() ; //hard is meet Solution s1 = new Solution(hPolice) ; s1.handleByPolice(10) ; //nice is meet Solution s2 = new Solution(nicePolice) ; s2.handleByPolice(10) ; } }
在jdk中,有用到strategy的有
1). Java.util.Collections#sort(List list, Comparator < ? super T > c)
2). java.util.Arrays#sort(T[], Comparator < ? super T > c)
The sort method use different Comparator in different situations。
要想知道 comparator /comparable的不同,可以查看
http://www.programcreek.com/2011/12/examples-to-demonstrate-comparable-vs-comparator-in-java/
strategy pattern和state pattern比较像,主要的不同在于:
State pattern involves changing the behavior of an object when the state of the object changes
while Strategy pattern is mainly about using different algorithm at different situation.