设计模式(八)-策略模式

2019/06/02

什么是策略模式 策略模式(strategy)定义了算法家族,分别封装起来,让他们能够互相替换,此模式让算法的变化不会影响到使用算法的用户。

简单来讲,策略模式就相当于指定了一个目标,有多种到达目标的方法或策略,尽管方法不同,最终结果相同。至于使用哪种策略则可以根据需要灵活选择。

策略模式类结构图 在这里插入图片描述 代码示例

策略接口

/**
 * @Author DevinLei
 */
interface  Strategy {

    void arrive();

}

StrategyA ,具体策略A

/**
 * @Author DevinLei
 */
public class StrategyA implements Strategy{

    @Override
    public  void arrive() {
        System.out.println("乘高铁从杭州去北京");
    }
}

StrategyB ,具体策略B

/**
 * @Author DevinLei
 */
public class StrategyB implements Strategy{

    @Override
    public void arrive() {
        System.out.println("乘飞机从杭州去北京");
    }
}

StrategyC ,具体策略C

/**
 * @Author DevinLei
 */
public class StrategyC implements Strategy{

    @Override
    public void arrive() {
        System.out.println("乘轮船从杭州去北京");
    }
}

Context 上下文类

/**
 * @Author DevinLei
 */
public class Context {

    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void  arrive(){
        strategy.arrive();
    }

}

测试类

/**
 * @Author DevinLei
 */
public class TestStrategy {
    public static void main(String[] args) {
        Context context;
        context = new Context(new StrategyA());
        context.arrive();
        context = new Context(new StrategyB());
        context.arrive();
        context = new Context(new StrategyC());
        context.arrive();
    }
}

输出结果

乘高铁从杭州去北京
乘飞机从杭州去北京
乘轮船从杭州去北京

应用场景 spring中的策略模式使用: 参考:https://blog.csdn.net/bntX2jSQfEHy7/article/details/82836682


一个有故事的程序员

(转载本站文章请注明作者和出处 纯洁的微笑-ityouknow

Show Disqus Comments

Post Directory