409
阿裏雲
技術社區[雲棲]
Java設計模式:策略模式
下麵是一個有關於策略模式的故事。假設Mike在開車的時候,會很頻繁的加速,有一天因為超速他被一個警察攔下來了。有可能這個警察會比較友好,沒開任何罰單就讓Mike把車開走了。(我們把這類型的警察稱之為“NicePolice”)。也有可能Mike遇到了一個不太友好的警察,然後這個警察給Mike出具了一張罰單。(我們把這類型的警察稱之為“HardPolice”)。
Mike其實並不知道他會遇到什麼類型的警察,直到他因為超速而被警察要求停車下來,實際上這就是一種程序當中“運行時”的概念,隻有在運行的時候,才知道,到底會遇到什麼類型的警察,實際上這就是“策略模式”。

先來定義一個策略的接口:Strategy
1 |
public interface Strategy {
|
2 |
public void processSpeeding( int speed);
|
再來定義兩種不同類型的Strategy:
1 |
public class NicePolice implements Strategy {
|
3 |
public void processSpeeding( int speed) {
|
5 |
.println( "This is your first time, be sure don't do it again!" );
|
1 |
public class HardPolice implements Strategy {
|
3 |
public void processSpeeding( int speed) {
|
4 |
System.out.println( "Your speed is " + speed
|
5 |
+ ", and should get a ticket!" );
|
定義一個需要依賴警察來處理超速問題的場景:
01 |
public class Situation {
|
02 |
private Strategy strategy;
|
04 |
public Situation(Strategy strategy){
|
05 |
this .strategy = strategy;
|
08 |
public void handleByPolice( int speed){
|
09 |
this .strategy.processSpeeding(speed);
|
最後,進行測試:
02 |
public static void main(String[] args) {
|
03 |
HardPolice hp = new HardPolice();
|
04 |
NicePolice ep = new NicePolice();
|
06 |
// In situation 1, a hard officer is met
|
07 |
// In situation 2, a nice officer is met
|
08 |
Situation s1 = new Situation(hp);
|
09 |
Situation s2 = new Situation(ep);
|
11 |
// the result based on the kind of police officer.
|
12 |
s1.handleByPolice( 10 );
|
13 |
s2.handleByPolice( 10 );
|
策略模式,實際上就是定義了一些算法,並把他們都封裝起來,使得他們之間可以互相替代。實際上對應上麵程序,就是定義了兩種算法(NicePolice以及HardPolice),由於他們都實現了Strategy這個接口,那麼對於依賴於這個接口的實例對象來說,可以動態的對這個依賴進行注入,從而達到運行時確定具體使用哪一種算法的目的。
最後更新:2017-05-23 17:03:22