MST

星途 面试题库

面试题:Java类设计的开闭原则与策略模式结合应用

假设你正在开发一个电商系统的促销模块,促销方式有满减、折扣等多种。请基于开闭原则,使用Java的策略模式来设计相关的类结构,阐述设计思路并给出核心代码示例。
26.6万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 定义促销策略接口:创建一个接口,包含促销计算的方法,不同的促销方式实现此接口。
  2. 实现具体促销策略类:分别实现满减、折扣等促销策略。
  3. 创建上下文类:在上下文类中持有促销策略接口的引用,通过构造函数传入具体的促销策略,调用促销计算方法。

核心代码示例

  1. 促销策略接口
public interface PromotionStrategy {
    double calculate(double originalPrice);
}
  1. 满减策略类
public class FullReductionStrategy implements PromotionStrategy {
    private double fullAmount;
    private double reductionAmount;

    public FullReductionStrategy(double fullAmount, double reductionAmount) {
        this.fullAmount = fullAmount;
        this.reductionAmount = reductionAmount;
    }

    @Override
    public double calculate(double originalPrice) {
        if (originalPrice >= fullAmount) {
            return originalPrice - reductionAmount;
        }
        return originalPrice;
    }
}
  1. 折扣策略类
public class DiscountStrategy implements PromotionStrategy {
    private double discount;

    public DiscountStrategy(double discount) {
        this.discount = discount;
    }

    @Override
    public double calculate(double originalPrice) {
        return originalPrice * discount;
    }
}
  1. 促销上下文类
public class PromotionContext {
    private PromotionStrategy promotionStrategy;

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

    public double executePromotion(double originalPrice) {
        return promotionStrategy.calculate(originalPrice);
    }
}
  1. 使用示例
public class Main {
    public static void main(String[] args) {
        // 使用满减策略
        PromotionContext fullReductionContext = new PromotionContext(new FullReductionStrategy(200, 50));
        double fullReductionResult = fullReductionContext.executePromotion(300);
        System.out.println("满减后的价格: " + fullReductionResult);

        // 使用折扣策略
        PromotionContext discountContext = new PromotionContext(new DiscountStrategy(0.8));
        double discountResult = discountContext.executePromotion(300);
        System.out.println("折扣后的价格: " + discountResult);
    }
}