面试题答案
一键面试设计思路
- 抽象基类与接口:定义一个抽象基类
Product
,包含所有产品共有的属性id
、name
、price
。让DigitalProduct
和PhysicalProduct
继承自Product
,分别添加各自特有的属性。 - 购物车接口:
CartItem
接口中使用Product
类型来兼容不同的产品,这样可以保证类型安全,同时具备扩展性。 - 业务逻辑:在购物车相关业务逻辑中,通过多态来处理不同类型的产品,使得添加商品、计算总价等操作可以高效实现。
- 扩展性:通过继承
Product
基类的方式,未来新增产品类型时,只需要创建新的类继承Product
并实现其特有属性和方法即可,购物车业务逻辑无需大量修改。
关键代码示例(以Java为例)
// 定义Product抽象类
abstract class Product {
private int id;
private String name;
private double price;
public Product(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
// DigitalProduct继承自Product
class DigitalProduct extends Product {
private String downloadUrl;
public DigitalProduct(int id, String name, double price, String downloadUrl) {
super(id, name, price);
this.downloadUrl = downloadUrl;
}
public String getDownloadUrl() {
return downloadUrl;
}
}
// PhysicalProduct继承自Product
class PhysicalProduct extends Product {
private double weight;
public PhysicalProduct(int id, String name, double price, double weight) {
super(id, name, price);
this.weight = weight;
}
public double getWeight() {
return weight;
}
}
// CartItem接口
class CartItem {
private Product product;
private int quantity;
public CartItem(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
public Product getProduct() {
return product;
}
public int getQuantity() {
return quantity;
}
public double calculateSubtotal() {
return product.getPrice() * quantity;
}
}
// 购物车类
class ShoppingCart {
private List<CartItem> items = new ArrayList<>();
public void addItem(Product product, int quantity) {
items.add(new CartItem(product, quantity));
}
public double calculateTotal() {
return items.stream()
.mapToDouble(CartItem::calculateSubtotal)
.sum();
}
}
通过上述设计,购物车业务逻辑能够高效且类型安全地实现,并且对于未来新增产品类型具有良好的扩展性。