21xrx.com
2025-04-16 10:18:44 Wednesday
文章检索 我的文章 写文章
策略模式实现简单的购物车
2023-06-15 20:28:14 深夜i     18     0

Java 设计模式期末考试

在本次 Java 设计模式期末考试中,我们将通过实现购物车的功能,来了解和掌握策略模式的使用方法。

在购物车中,我们需要对不同类型的商品进行价格计算,并根据不同的折扣策略来确定最终的价格。这时候,我们可以使用策略模式来实现。

首先,我们需要定义一个商品类,包含商品名称和价格两个属性:

public class Item {
  private String name;
  private double price;
  public Item(String name, double price)
    this.name = name;
    this.price = price;
  
  // getter and setter methods
  @Override
  public String toString() {
    return "Item{" +
        "name='" + name + '\'' +
        ", price=" + price +
        '}';
  }
}

接下来,我们定义一个抽象策略类 DiscountStrategy,其中包含一个抽象方法计算价格:

public abstract class DiscountStrategy {
  public abstract double calculatePrice(Item item);
}

然后,我们定义两个具体策略类,分别是没有折扣的策略 NoDiscountStrategy 和打八折的策略 EightOffDiscountStrategy:

public class NoDiscountStrategy extends DiscountStrategy {
  @Override
  public double calculatePrice(Item item) {
    return item.getPrice();
  }
}
public class EightOffDiscountStrategy extends DiscountStrategy {
  @Override
  public double calculatePrice(Item item) {
    return item.getPrice() * 0.8;
  }
}

最后,我们定义一个购物车类 ShoppingCart,其中包含一个 items 列表和一个 discountStrategy 属性:

import java.util.ArrayList;
import java.util.List;
public class ShoppingCart {
  private List
  items;
 
  private DiscountStrategy discountStrategy;
  public ShoppingCart() {
    this.items = new ArrayList<>();
    this.discountStrategy = new NoDiscountStrategy();
  }
  public void addItem(Item item) {
    items.add(item);
  }
  public void removeItem(Item item) {
    items.remove(item);
  }
  public double calculateTotalPrice() {
    double totalPrice = 0;
    for (Item item : items) {
      totalPrice += discountStrategy.calculatePrice(item);
    }
    return totalPrice;
  }
  public void setDiscountStrategy(DiscountStrategy discountStrategy)
    this.discountStrategy = discountStrategy;
  
}

上面的代码实现了购物车的基本功能,并且通过使用策略模式,可以方便地实现不同类型的折扣策略。比如,我们可以这样来使用购物车:

public static void main(String[] args) {
  ShoppingCart cart = new ShoppingCart();
  cart.addItem(new Item("Phone", 5000));
  cart.addItem(new Item("Laptop", 8000));
  double totalPrice = cart.calculateTotalPrice();
  System.out.println("Total price: " + totalPrice);
  DiscountStrategy discountStrategy = new EightOffDiscountStrategy();
  cart.setDiscountStrategy(discountStrategy);
  totalPrice = cart.calculateTotalPrice();
  System.out.println("Total price with 20% off: " + totalPrice);
}

运行结果如下:

Total price: 13000.0
Total price with 20% off: 10400.0

从上面的代码可以看出,我们先创建了一个购物车对象,然后向购物车中添加了两个商品。在没有设置折扣策略的情况下,购物车的总价格为原始价格的和。接着,我们设置了折扣策略为八折,此时购物车的总价格为打折之后的价格。

通过本次实验,我们可以学习到以下几个设计模式关键词:

1. 策略模式

2. 抽象类

3. 实现类

  
  

评论区