设计思路
- 定义促销策略接口:创建一个接口,包含促销计算的方法,不同的促销方式实现此接口。
- 实现具体促销策略类:分别实现满减、折扣等促销策略。
- 创建上下文类:在上下文类中持有促销策略接口的引用,通过构造函数传入具体的促销策略,调用促销计算方法。
核心代码示例
- 促销策略接口
public interface PromotionStrategy {
double calculate(double originalPrice);
}
- 满减策略类
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;
}
}
- 折扣策略类
public class DiscountStrategy implements PromotionStrategy {
private double discount;
public DiscountStrategy(double discount) {
this.discount = discount;
}
@Override
public double calculate(double originalPrice) {
return originalPrice * discount;
}
}
- 促销上下文类
public class PromotionContext {
private PromotionStrategy promotionStrategy;
public PromotionContext(PromotionStrategy promotionStrategy) {
this.promotionStrategy = promotionStrategy;
}
public double executePromotion(double originalPrice) {
return promotionStrategy.calculate(originalPrice);
}
}
- 使用示例
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);
}
}