MST

星途 面试题库

面试题:Java中策略模式在复杂系统中的应用场景

请描述在一个电商系统中,如何使用Java的策略模式来处理不同类型商品的促销活动,比如满减、打折、赠品等,并简要说明策略模式的优点。
16.3万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

1. 定义促销活动接口

public interface PromotionStrategy {
    void executePromotion();
}

2. 实现不同促销策略类

满减策略

public class FullReductionPromotionStrategy implements PromotionStrategy {
    @Override
    public void executePromotion() {
        System.out.println("执行满减促销活动");
    }
}

打折策略

public class DiscountPromotionStrategy implements PromotionStrategy {
    @Override
    public void executePromotion() {
        System.out.println("执行打折促销活动");
    }
}

赠品策略

public class GiftPromotionStrategy implements PromotionStrategy {
    @Override
    public void executePromotion() {
        System.out.println("执行赠品促销活动");
    }
}

3. 创建促销活动上下文类

public class PromotionContext {
    private PromotionStrategy promotionStrategy;

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

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

4. 在电商系统中使用

public class EcommerceSystem {
    public static void main(String[] args) {
        // 处理满减商品
        PromotionContext fullReductionContext = new PromotionContext(new FullReductionPromotionStrategy());
        fullReductionContext.executePromotion();

        // 处理打折商品
        PromotionContext discountContext = new PromotionContext(new DiscountPromotionStrategy());
        discountContext.executePromotion();

        // 处理赠品商品
        PromotionContext giftContext = new PromotionContext(new GiftPromotionStrategy());
        giftContext.executePromotion();
    }
}

策略模式的优点

  • 可维护性高:每个促销策略都被封装在独立的类中,当需要修改或添加新的促销策略时,只需要修改或新增对应的策略类,而不会影响到其他部分的代码。
  • 可扩展性强:如果电商系统需要新增一种促销活动,例如限时抢购,只需要创建一个实现 PromotionStrategy 接口的新类,然后在需要的地方使用 PromotionContext 来调用即可,无需修改大量现有代码。
  • 提高代码复用性:不同的促销策略可以在多个地方复用,避免了重复代码的出现。例如满减策略可能在不同的商品分类或促销组合中使用。