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

什么是策略模式
策略模式(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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值