手写一个简单易懂的策略模式

 策略模式的核心思想是将算法的定义和使用分离,把一系列算法封装成一个个独立的类,使得它们可以相互替换,从而使程序的扩展性和维护性更强。

// 定义抽象的促销策略接口
interface PromotionStrategy {
    void doPromotion();
}

// 具体的促销策略类:满减策略
class FullReducePromotion implements PromotionStrategy {
    @Override
    public void doPromotion() {
        System.out.println("进行满减促销活动,满 300 减 50。");
    }
}

// 具体的促销策略类:打折策略
class DiscountPromotion implements PromotionStrategy {
    @Override
    public void doPromotion() {
        System.out.println("进行打折促销活动,商品打 8 折。");
    }
}

// 具体的促销策略类:赠品策略
class GiveawayPromotion implements PromotionStrategy {
    @Override
    public void doPromotion() {
        System.out.println("进行赠品促销活动,购买商品赠送小礼品。");
    }
}

// 上下文类,持有具体的促销策略实例,并调用其促销方法
class ShoppingContext {
    private PromotionStrategy promotionStrategy;

    public ShoppingContext(PromotionStrategy promotionStrategy) {
        this.promotionStrategy = promotionStrategy;
    }

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

// 测试类
public class StrategyPatternExample {
    public static void main(String[] args) {
        // 使用满减策略进行促销
        ShoppingContext fullReduceContext = new ShoppingContext(new FullReducePromotion());
        fullReduceContext.executePromotion();

        // 使用打折策略进行促销
        ShoppingContext discountContext = new ShoppingContext(new DiscountPromotion());
        discountContext.executePromotion();

        // 使用赠品策略进行促销
        ShoppingContext giveawayContext = new ShoppingContext(new GiveawayPromotion());
        giveawayContext.executePromotion();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值