在电商系统中有多种促销活动,比如满减、打折、返现等,而每种促销活动都有不同的计算逻辑。我们可以使用工厂模式来创建不同类型的促销策略对象,并使用策略模式来根据用户选择的促销类型执行相应的促销计算。下面直接上代码.
1.定义策略接口(Strategy Interface):PaymentStrategy.java
public interface PromotionStrategy {
double applyPromotion(double price);
}
2.实现策略接口(折扣策略):CreditCardPayment.java
public class DiscountPromotion implements PromotionStrategy {
private double discount;
public DiscountPromotion(double discount) {
this.discount = discount;
}
@Override
public double applyPromotion(double price) {
return price * (1 - discount);
}
}
3.实现策略接口(满减策略):FullReductionPromotion.java
public class FullReductionPromotion implements PromotionStrategy {
private double threshold;
private double reduction;
public FullReductionPromotion(double threshold, double reduction) {
this.threshold = threshold;
this.reduction = reduction;
}
@Override
public double applyPromotion(double price) {
return price >= threshold ? price - reduction : price;
}
}
4.定义工厂类(Factory):PromotionFactory.java
public class PromotionFactory {
public static PromotionStrategy createPromotionStrategy(String promotionType) {
switch (promotionType) {
case "discount":
return new DiscountPromotion(0.2); // 20% discount
case "full_reduction":
return new FullReductionPromotion(100, 30); // If total price >= 100, reduce 30
default:
throw new IllegalArgumentException("Unknown promotion type: " + promotionType);
}
}
}
5.测试代码
public class FactoryAndStrategyDemo {
public static void main(String[] args) {
String promotionType = "discount"; // or "full_reduction"
double totalPrice = 150;
PromotionStrategy promotionStrategy = PromotionFactory.createPromotionStrategy(promotionType);
double finalPrice = promotionStrategy.applyPromotion(totalPrice);
System.out.println("Promotion Type: " + promotionType);
System.out.println("Total Price: $" + totalPrice);
System.out.println("Final Price after Promotion: $" + finalPrice);
}
}
在这个示例中,工厂模式(PromotionFactory)负责创建不同类型的促销策略对象,策略模式(PromotionStrategy)则定义了促销计算的接口。客户端代码根据用户选择的促销类型使用工厂创建相应的策略对象,并通过策略对象执行促销计算,无需关心具体的促销逻辑,实现了代码的解耦和灵活性。
有的朋友可能会注意到,多种折扣可能会互相叠加使用, 像下面这样,这时代码就又不优雅了.
public static void main(String[] args) {
double totalPrice = 150;
PromotionStrategy discountStrategy = PromotionFactory.createPromotionStrategy("discount");
PromotionStrategy fullReductionStrategy = PromotionFactory.createPromotionStrategy("full_reduction");
double tempPrice = discountStrategy.applyPromotion(totalPrice);
double finalPrice = fullReductionStrategy.applyPromotion(tempPrice);
System.out.println("Total Price: $" + totalPrice);
System.out.println("Final Price after Promotion: $" + finalPrice);
}
这种情况我们可以考虑用建造者模式去改造代码(未完待续)