iT邦幫忙

2021 iThome 鐵人賽

DAY 28
0
自我挑戰組

馬克的軟體架構小筆記系列 第 28

30-28 之 DDD 戰術篇1 - Entity 與 Value Object

  • 分享至 

  • twitterImage
  •  

在簡單談完戰略篇後,接下來要進行戰行篇,也就是將 DDD 實際的應用到程式碼中。

在 DDD 戰術層級有兩個非常重要的概念 :

  • Entity
  • Value Object

接下來這篇文章要先來談談這東西。

什麼是 Entity ?

An Entity is an object defined not by its attributes, but a thread of continuity and identity, which spans the life of a system and can extend beyond it.

我自已簡單的理解為 :

它是一個物件,有唯一標識 + 業務行為方法

  • 這些 Entity 都是充血模型,也就是它有屬性與業務行為。而另一種貧血模型則只有遲性,它的業務行為都放在 service 層實現。
  • 一個 Entity 可能對應到多個資料庫持久化物件 ( Persistent Object PO )
  • 多個 Entity 可能對應到一個 PO。例如有些情況下,為了性能,會將 customer 顧客 與 account 帳戶資訊存在同一張表。

簡單舉個範例,假設我們有個錢包,而將它寫成 Entity 如下,這就是一個實體 :

class Wallet{
    id: string
    value: number 
    addMoney(deposit : number): void{
        this.value += deposit
    }
    subtractMoney(debit: number): void{
        if(this.value < debit){
            this.value -= debit
        }
    }
}

那這個是從戰略層級那來的 ? 是我們之前討論的 Domain StoryTelling 下圖的 Work Object 嗎 ? 不 ~ 不是,比較準確的說,那個之後會談的 Aggregate 比較像,而 entity 只是它裡面的某個組成。

https://ithelp.ithome.com.tw/upload/images/20211012/20089358epeK24PpjM.png

DDD Entity VS Domain Model

什麼是 Value Object ?

與 Entity 的差別在於,沒有唯一標識

舉個例子,例如 Money,它事實上只需要有兩個屬性,一個代表幣別,一個代表值,它不需要有個唯一標識說他是整個系統中唯一的。

class Money{
    value: number
    currency: string
}

通常會與 entity 這樣一起用

class Wallet{
    id: string
    value: Money  <---------------------- 這裡
    addMoney(deposit : number): void{
        this.value += deposit
    }
    subtractMoney(debit: number): void{
        if(this.value < debit){
            this.value -= debit
        }
    }
}

參考資料


上一篇
30-27 之 DDD 戰略設計 3 - 實作方法之 Domain Storytelling 領域敘事 ( 未完成 )
下一篇
30-29 之 DDD 戰術篇 2 - Aggregate ( 未完成 )
系列文
馬克的軟體架構小筆記29
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言