使用策略模式 做 打折
时间: 2023-11-10 22:07:39 浏览: 46
策略模式是一种行为型设计模式,它定义了一系列算法,将每个算法封装成单独的类,并使它们可以互换。使用策略模式可以在运行时动态选择算法,从而实现不同的行为。
在打折场景中,可以定义一个 DiscountStrategy 接口,其中包含一个 calculateDiscount 方法,用于计算打折后的价格。然后,根据不同的打折策略,实现不同的 DiscountStrategy 实现类,如 PercentageDiscountStrategy、FixedDiscountStrategy 等。
具体实现如下:
```java
public interface DiscountStrategy {
double calculateDiscount(double price);
}
public class PercentageDiscountStrategy implements DiscountStrategy {
private double discountRate;
public PercentageDiscountStrategy(double discountRate) {
this.discountRate = discountRate;
}
@Override
public double calculateDiscount(double price) {
return price * (1 - discountRate);
}
}
public class FixedDiscountStrategy implements DiscountStrategy {
private double discountAmount;
public FixedDiscountStrategy(double discountAmount) {
this.discountAmount = discountAmount;
}
@Override
public double calculateDiscount(double price) {
if (price > discountAmount) {
return price - discountAmount;
} else {
return price;
}
}
}
public class DiscountContext {
private DiscountStrategy strategy;
public DiscountContext(DiscountStrategy strategy) {
this.strategy = strategy;
}
public double getPriceAfterDiscount(double price) {
return strategy.calculateDiscount(price);
}
}
```
然后,在客户端代码中,可以根据需要选择相应的打折策略,并将其传递给 DiscountContext:
```java
DiscountStrategy strategy = new PercentageDiscountStrategy(0.2);
DiscountContext context = new DiscountContext(strategy);
double price = 100.0;
double priceAfterDiscount = context.getPriceAfterDiscount(price);
System.out.println("Price after discount: " + priceAfterDiscount);
```
这样,就可以根据需要选择不同的打折策略,而不必修改客户端代码。