您当前的位置: 首页 > 

设计模式系列教程(13) - 策略模式

杨林伟 发布时间:2019-10-29 16:08:18 ,浏览量:2

代码已上传至Github,有兴趣的同学可以下载来看看:https://github.com/ylw-github/Java-DesignMode

1. 什么是策略模式

定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。

2. 策略模式应用场景

策略模式的用意是针对一组算法或逻辑,将每一个算法或逻辑封装到具有共同接口的独立的类中,从而使得它们之间可以相互替换。策略模式使得算法或逻辑可以在不影响到客户端的情况下发生变化。说到策略模式就不得不提及OCP(Open Closed Principle) 开闭原则,即对扩展开放,对修改关闭。策略模式的出现很好地诠释了开闭原则,有效地减少了分支语句。

3. 案例

此代码通过模拟不同会员购物车打折力度不同分为三种策略,初级会员,中级会员,高级会员。

Strategy:

/*
 * 策略模式 定义抽象方法 所有支持公共接口
 */
public abstract class Strategy {
    //算法方法
    abstract void algorithmInterface();
}

StrategyA:

public class StrategyA extends Strategy{
    @Override
    void algorithmInterface() {
        System.out.println("算法A");
    }
}

StrategyB:

public class StrategyB extends Strategy{
    @Override
    void algorithmInterface() {
        System.out.println("算法B");
    }
}

StrategyC:

public class StrategyC extends Strategy{
    @Override
    void algorithmInterface() {
        System.out.println("算法C");
    }
}

Context 使用上下文维护算法策略:

public class Context {

    Strategy strategy;

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

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

Client:

public class Client {

    public static void main(String[] args) {
        Context context;
        context = new Context(new StrategyA());
        context.algorithmInterface();
        context = new Context(new StrategyB());
        context.algorithmInterface();
        context = new Context(new StrategyC());
        context.algorithmInterface();
    }
}

在这里插入图片描述

总结

在这里插入图片描述

关注
打赏
1688896170
查看更多评论

杨林伟

暂无认证

  • 2浏览

    0关注

    3183博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.4728s