設計模式筆記(二):策略模式

應用場景:

1、如果在一個系統裏面有許多類,它們之間的區別僅在於它們的行爲,那麼使用策略模式可以動態地讓一個對象在許多行爲中選擇一種行爲。

2、一個系統需要動態地在幾種算法中選擇一種。

3、如果一個對象有很多的行爲,如果不用恰當的模式,這些行爲就只好使用多重的條件選擇語句來實現。

實現步驟:

以人喫飯的方式不同來舉例。

1、定義一個接口,接口中定義行爲方法;

public interface EatStrategy {
    void eat();//喫飯策略
}

 

2、定義多個需要實現該行爲方法的實現類;

單身狗,只能一個人喫飯

public class SingleEat implements EatStrategy {
    @Override
    public void eat() {
        System.out.println("一個人喫");
    }
}

有對象的人,兩個人喫飯

public class DoubleEat implements EatStrategy {
    @Override
    public void eat() {
        System.out.println("兩個人喫");
    }
}

 

3、定義容器類(Person),組合行爲方法的實現類(EatStrategy),需要時調用實現類的方法即可。

張三現在20歲,職業程序員,平時工作太忙,來不及找對象,所以喫飯只能採用單身狗方式:

public class Person {

    private EatStrategy eatStrategy;

    public Person(EatStrategy eatStrategy){
        this.eatStrategy = eatStrategy;//構造方法設置喫飯實例
    }

    public void setEatStrategy(EatStrategy eatStrategy) {
        this.eatStrategy = eatStrategy;//setter方法設置喫飯實例
    }

    public void eat(){
        eatStrategy.eat();//使用喫飯實例喫飯
    }

    public static void main(String[] args) {
        Person person = new Person(new SingleEat());
        person.eat();
    }
}

 

 

10年過去了,張三當上了公司研發總監,陸續買房買車,找女友更是不在話下。現在張三喫飯變爲兩個人吃了:

public class Person {

    private EatStrategy eatStrategy;

    public Person(EatStrategy eatStrategy) {
        this.eatStrategy = eatStrategy;
    }

    public void setEatStrategy(EatStrategy eatStrategy) {
        this.eatStrategy = eatStrategy;
    }

    public void eat() {
        eatStrategy.eat();
    }

    public static void main(String[] args) {
        Person person = new Person(new SingleEat());
        person.eat();
        //ten years later
        person.setEatStrategy(new DoubleEat());//調用setter方法,切換喫飯策略
        person.eat();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章