设计模式 - 策略模式

定义:策略模式定义了算法簇,分别封装起来,让它们之间可以互相替代,此模式让算法的变化独立于使用算法的客户。

对象: 环境对象(Context):该类中实现了对抽象策略中定义的接口或者抽象类的引用。
         抽象策略对象(Strategy):它可由接口或抽象类来实现。
       具体策略对象(ConcreteStrategy):它封装了实现同不功能的不同算法或行为。

代码示例:

场景:我想要看不同的西游记片段,并且以后还可以添加或扩充其他的片段以供我观看。

抽象策略对象,提供不同算法和行为的入口。

package com.strategy;

public interface SceneStrategy {
    
    void showScene();

}
View Code

 

具体策略对象,实现抽象策略的方法,适应不同的算法和行为。

提供观看三打白骨精的场景。

package com.strategy;

public class ThreeDozenBonesSceneStrategy implements SceneStrategy {

    @Override
    public void showScene() {
        System.out.println("西游记之三打白骨精");
    }

}
View Code

 

提供女儿国的场景。

package com.strategy;

public class DaughterCountrySceneStrategy implements SceneStrategy {

    @Override
    public void showScene() {
        System.out.println("西游记之女儿国");
    }

}
View Code

 

提高真假美猴王的场景。

package com.strategy;

public class TrueMonkeyKingSceneStrategy implements SceneStrategy {

    @Override
    public void showScene() {
        System.out.println("西游记之真假美猴王");
    }

}
View Code

 

环境对象,使用不同算法和行为的入口。

package com.strategy;

public class WatchScene {
    
    private SceneStrategy sceneStrategy;

    public WatchScene(SceneStrategy sceneStrategy) {
        super();
        this.sceneStrategy = sceneStrategy;
    }
    
    public void orderSceneShow(){
        sceneStrategy.showScene();
    }

}
View Code

 

测试策略模式代码

package com.strategy;

public class TestStrategy {

    public static void main(String[] args) {
        
        SceneStrategy daughterCountrySceneStrategy = new DaughterCountrySceneStrategy();
        WatchScene watchScene = new WatchScene(daughterCountrySceneStrategy);
        watchScene.orderSceneShow();
        
        SceneStrategy threeDozenBonesSceneStrategy = new ThreeDozenBonesSceneStrategy();
        watchScene = new WatchScene(threeDozenBonesSceneStrategy);
        watchScene.orderSceneShow();
        
        SceneStrategy trueMonkeyKingSceneStrategy = new TrueMonkeyKingSceneStrategy();
        watchScene = new WatchScene(trueMonkeyKingSceneStrategy);
        watchScene.orderSceneShow();

    }

}
View Code

 

好处:

  1、可以动态的改变对象的行为,以根据不同的需要或场景提供不同的算法和实现行为,但策略模式在每一个时刻只能使用一个具体的策略实现对象。
坏处:
  1、客户端必须知道所有的策略类,并了解每个实现类的具体作用来自行决定使用哪一个策略类;
  2、如果要实现的算法和行为比较多,那么策略模式将造成产生很多的策略类,如要看西游记81难的场景,就要实现81个实现类。
 
posted @ 2017-05-30 13:01  吉良吉影的冒险  阅读(118)  评论(0编辑  收藏  举报