写点什么

[ Golang 中的 DDD 实践] 值对象

用户头像
baiyutang
关注
发布于: 刚刚

译者:baiyutang

原文:https://levelup.gitconnected.com/practical-ddd-in-golang-value-object-4fc97bcad70


让我们开始 Golang 中最重要的模式领域驱动设计之旅:值对象。


简单而美好

type Money struct {  Value    float64  Currency Currency}func (m Money) ToHTML() string {  returs fmt.Sprintf(`%.2f%s`, m.Value, m.Currency.HTML)}type Salutation stringfunc (s Salutation) IsPerson() bool {  returs s != "company" }  type Color struct {  Red   byte  Green byte  Blue  byte}func (c Color) ToCSS() string {  return fmt.Sprintf(`rgb(%d, %d, %d)`, c.Red, c.Green, c.Blue)}type Address struct {  Street   string  Number   int  Suffix   string  Postcode int}type Phone struct {  CountryPrefix string  AreaCode      string  Number        string}
复制代码

复制代码


身份与相等

// checking equality for value objectsfunc (c Color) EqualTo(other Color) bool {  return c.Red == other.Red && c.Green == other.Green && c.Blue == other.Blue}// checking equality for value objectsfunc (m Money) EqualTo(other Money) bool {  return m.Value == other.Value && m.Currency.EqualTo(other.Currency)}// checking equality for entitiesfunc (c Currency) EqualTo(other Currency) bool {  return c.ID.String() == other.ID.String()}
复制代码

复制代码


type Coin struct {  Value Money  Color Color}type Colors []Color
复制代码

复制代码


// value object on web servicetype Currency struct {  Code string  HTML int}// entity on payment servicetype Currency struct {  ID   uuid.UUID  Code string  HTML int}
复制代码

复制代码


明确

type Birthday time.Timefunc (b Birthday) IsYoungerThen(other time.Time) bool {  return time.Time(b).After(other)}func (b Birthday) IsAdult() bool {  return time.Time(b).AddDate(18, 0, 0).Before(time.Now())}const (  Freelancer = iota  Partnership  LLC  Corporation)type LegalForm intfunc (s LegalForm) IsIndividual() bool {  return s == Freelancer}func (s LegalForm) HasLimitedResponsability() bool {  return s == LLC || s == Corporation}
复制代码


发布于: 刚刚阅读数: 3
用户头像

baiyutang

关注

广州 2017.12.13 加入

Microservices | Golang | Cloud Nitive | “Smart work,Not hard”

评论

发布
暂无评论
[ Golang 中的 DDD 实践] 值对象