设计模式 – 策略模式

导读:本篇文章讲解 设计模式 – 策略模式,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

策略模式

策略模式(Strategy Pattern)是指定义了算法家族、分别封装起来,让它们之间可以互
相替换,此模式让算法的变化不会影响到使用算法的用户。

使用场景

1、假如系统中有很多类,而他们的区别仅仅在于他们的行为不同。
2、一个系统需要动态地在几种算法中选择一种。

案例

购物时有优惠活动,优惠策略会有很多种可能如:领取优惠券抵扣、返现促销、拼团优惠。下面我们用代码来模拟:

在这里插入图片描述

public interface PromotionStrategy {

    void doPromotion();

}

public class CashbackStrategy implements PromotionStrategy {

    public void doPromotion() {
        System.out.println("返现促销,返回的金额转到支付宝账号");
    }

}


public class CouponStrategy implements PromotionStrategy {
    public void doPromotion() {
        System.out.println("领取优惠券,购物价格价格直接减优惠券面值抵扣");
    }
}



public class EmptyStrategy implements PromotionStrategy {

    public void doPromotion() {

        System.out.println("无促销活动");
    }
}




public class GroupbuyStrategy implements PromotionStrategy {

    public void doPromotion() {

        System.out.println("拼团,满 20 人成团,全团享受团购价");

    }
}









public class PromotionActivity {

    private PromotionStrategy promotionStrategy;

    public PromotionActivity(PromotionStrategy promotionStrategy) {
        this.promotionStrategy = promotionStrategy;

    }

    public void execute() {
        promotionStrategy.doPromotion();
    }
}


public class StrategyTest {

    public static void main(String[] args) {
        PromotionActivity activity618 = new PromotionActivity(new CouponStrategy());
        PromotionActivity activity1111 = new PromotionActivity(new CashbackStrategy());
        activity618.execute();
        activity1111.execute();
    }

}

在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/15113.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!