MST
星途 面试题库

面试题:Java领域驱动设计之实体类构建

在Java领域驱动设计中,假设我们正在开发一个电商系统,有一个商品实体类Product。请阐述如何合理定义Product实体类的属性、方法以及它应该遵循哪些领域驱动设计的原则,例如不变性原则等。同时,请给出Product实体类的大致代码示例。
42.1万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

1. 属性定义

在电商系统中,Product实体类的属性应反映商品的核心特征。例如:

  • 唯一标识id,用于唯一确定一个商品。
  • 名称name,商品的名称。
  • 价格price,商品的售价。
  • 描述description,对商品的详细描述。
  • 库存数量stockQuantity,记录商品当前的库存。

2. 方法定义

  • 获取属性方法:为每个属性提供getter方法,用于外部获取属性值。
  • 业务方法
    • reduceStock(int quantity):用于减少商品库存,当有订单生成时调用。
    • isInStock():判断商品是否有库存。

3. 遵循的领域驱动设计原则

  • 不变性原则:实体的某些关键状态在特定业务规则下应保持不变。例如,商品一旦创建,其id不应被修改。
  • 单一职责原则Product实体类应专注于商品自身的业务逻辑,如库存管理等,不应承担与商品无关的职责,如订单处理。
  • 聚合原则Product可以作为一个聚合根,它与其他实体(如订单中的商品项)存在关联关系,并且对其关联实体的生命周期有一定的管理职责。

4. 代码示例

public class Product {
    private Long id;
    private String name;
    private BigDecimal price;
    private String description;
    private int stockQuantity;

    public Product(Long id, String name, BigDecimal price, String description, int stockQuantity) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.description = description;
        this.stockQuantity = stockQuantity;
    }

    // Getter方法
    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public String getDescription() {
        return description;
    }

    public int getStockQuantity() {
        return stockQuantity;
    }

    // 业务方法
    public void reduceStock(int quantity) {
        if (quantity <= stockQuantity) {
            stockQuantity -= quantity;
        } else {
            throw new IllegalArgumentException("Not enough stock");
        }
    }

    public boolean isInStock() {
        return stockQuantity > 0;
    }
}