MST

星途 面试题库

面试题:复杂业务场景下TypeScript接口扩展与组合的优化

在一个电商系统中,有基础接口`Product`,包含`id`、`name`、`price`属性。现在有两种特殊产品类型接口`DigitalProduct`(继承`Product`并新增`downloadUrl`属性)和`PhysicalProduct`(继承`Product`并新增`weight`属性)。另外,有一个购物车接口`CartItem`,需要能兼容这两种产品类型。请设计一套合理的接口扩展与组合方案,使得购物车相关的业务逻辑(如添加商品、计算总价等)能够高效且类型安全地实现。同时,考虑到未来可能会新增其他产品类型,如何设计才能让系统具有良好的扩展性?请给出详细的设计思路和关键代码示例。
38.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 抽象基类与接口:定义一个抽象基类Product,包含所有产品共有的属性idnameprice。让DigitalProductPhysicalProduct继承自Product,分别添加各自特有的属性。
  2. 购物车接口CartItem接口中使用Product类型来兼容不同的产品,这样可以保证类型安全,同时具备扩展性。
  3. 业务逻辑:在购物车相关业务逻辑中,通过多态来处理不同类型的产品,使得添加商品、计算总价等操作可以高效实现。
  4. 扩展性:通过继承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();
    }
}

通过上述设计,购物车业务逻辑能够高效且类型安全地实现,并且对于未来新增产品类型具有良好的扩展性。