java商场满减活动_Java使用策略模式解决商场促销商品问题示例
时间: 2024-01-15 08:02:37 浏览: 51
好的,我了解你的问题。下面是一个使用策略模式解决商场促销商品问题的Java示例:
假设商场有一个满减活动,如果购买的商品总价超过100元,可以减去10元;如果购买的商品总价超过200元,可以减去30元。我们可以使用策略模式来实现这个活动。
首先,我们创建一个接口`DiscountStrategy`来表示折扣策略:
```java
public interface DiscountStrategy {
double getDiscount(double totalPrice);
}
```
然后,我们创建两个实现类`TenOffStrategy`和`ThirtyOffStrategy`来分别表示满100减10和满200减30的折扣策略:
```java
public class TenOffStrategy implements DiscountStrategy {
@Override
public double getDiscount(double totalPrice) {
return totalPrice >= 100 ? 10 : 0;
}
}
public class ThirtyOffStrategy implements DiscountStrategy {
@Override
public double getDiscount(double totalPrice) {
return totalPrice >= 200 ? 30 : 0;
}
}
```
最后,我们创建一个`DiscountContext`类来管理折扣策略,根据购买商品的总价来选择合适的折扣策略:
```java
public class DiscountContext {
private DiscountStrategy strategy;
public DiscountContext(double totalPrice) {
if (totalPrice >= 200) {
strategy = new ThirtyOffStrategy();
} else if (totalPrice >= 100) {
strategy = new TenOffStrategy();
} else {
strategy = null;
}
}
public double getDiscount() {
return strategy == null ? 0 : strategy.getDiscount();
}
}
```
这样,我们就可以通过`DiscountContext`类来获取购买商品所能享受的折扣了。例如,如果购买了总价为150元的商品,可以这样使用:
```java
DiscountContext context = new DiscountContext(150);
double discount = context.getDiscount(); // discount = 10
```
这就是一个使用策略模式解决商场促销商品问题的Java示例。希望能对你有所帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)