策略模式的设计模式 - V.代码示例 - Java
最编程
2024-09-29 17:14:11
...
以下是一个详细的Java代码示例,展示了策略模式在电商促销策略中的应用。
// 策略接口
public interface PromotionStrategy {
double calculateDiscount(double originalPrice);
}
// 具体策略A:满减策略
public class FullDiscountStrategy implements PromotionStrategy {
private double threshold; // 满减门槛
private double discount; // 减免金额
public FullDiscountStrategy(double threshold, double discount) {
this.threshold = threshold;
this.discount = discount;
}
@Override
public double calculateDiscount(double originalPrice) {
if (originalPrice >= threshold) {
return discount;
}
return 0;
}
}
// 具体策略B:打折策略
public class DiscountRateStrategy implements PromotionStrategy {
private double discountRate; // 折扣率
public DiscountRateStrategy(double discountRate) {
this.discountRate = discountRate;
}
@Override
public double calculateDiscount(double originalPrice) {
return originalPrice * discountRate;
}
}
// 上下文类
public class PromotionContext {
private PromotionStrategy strategy;
public PromotionContext(PromotionStrategy strategy) {
this.strategy = strategy;
}
public double applyPromotion(double originalPrice) {
double discount = strategy.calculateDiscount(originalPrice);
return originalPrice - discount;
}
// 允许在运行时更换策略
public void setStrategy(PromotionStrategy strategy) {
this.strategy = strategy;
}
}
// 客户端代码
public class StrategyPatternDemo {
public static void main(String[] args) {
// 使用满减策略
PromotionContext context = new PromotionContext(new FullDiscountStrategy(100, 20));
System.out.println("原价120元,满100减20后价格为:" + context.applyPromotion(120));
// 切换为打折策略
context.setStrategy(new DiscountRateStrategy(0.8)); // 8折优惠
System.out.println("原价120元,打8折后价格为:" + context.applyPromotion(120));
}
}
在这个示例中,我们定义了一个PromotionStrategy接口,用于定义促销策略的公共接口。然后,我们实现了两个具体的促销策略类:FullDiscountStrategy(满减策略)和DiscountRateStrategy(打折策略)。PromotionContext类作为上下文类,维护了对策略对象的引用,并提供了applyPromotion方法来应用促销策略。在客户端代码中,我们创建了PromotionContext对象,并通过设置不同的策略对象来演示了促销策略的动态切换。