设计模式 – 策略模式

it2025-04-03  16

策略模式

策略模式(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(); } }

最新回复(0)