如何写出漂亮的构造函数 option funciton

1. Golang里面没有构造函数,但是Golang却可以像C++一样实现类似继承、构造函数一样等面向对象编程的思想和方法

Golang里面要实现相关的构造函数定义可以通过通过new来创建构造函数,

通过new一个对象,或者利用Golang本身的&方式来生成一个对象并返回一个对象指针

package main

type Book struct {
    Title string
    ISBN  string
}

func NewBook(t string) *Book {
    return &Book{
        Title: t,
        ISBN:  "",
    }
}

func NewBook2(t string, i string) *Book {
    return &Book{
        Title: t,
        ISBN:  i,
    }
}

func main() {
    _ = NewBook("早点下班的go语言学习法")
    _ = NewBook2("早点下班的go语言学习法", "20230101")
}

// How To Make Constructor Better
View Code

 

2.上面这种有重复,显然不优雅。可以利用配置参数的形式添加

package main

type Book__ struct {
    cfg *Config
}
type Config struct {
    Title string
    ISBN  string
}

func NewBook__(cfg *Config) *Book__ {
    return &Book__{cfg}
}

func main__() {
    _ = NewBook__(&Config{
        Title: "早点下班的go语言学习法",
        ISBN:  "20230101",
    })
}
View Code

3.上面违反了开闭原则,字段部分修改,客户端报错,并也要修改

package main

type Book___ struct {
    Title string
    Code  string
}
type Option func(*Book___)

func NewBook_(options ...Option) *Book___ {
    b := &Book___{}
    for _, option := range options {
        option(b)
    }
    return b
}

func WithTitle(title string) Option {
    return func(b *Book___) {
        b.Title = title
    }
}

func WithISBN(ISBN string) Option {
    return func(b *Book___) {
        b.Code = ISBN
    }
}

func main_() {
    _ = NewBook_(
        WithTitle("Go for Dummies"), WithISBN("1234567890"),
    )
}
View Code

 

posted @ 2023-03-03 15:28  易先讯  阅读(8)  评论(0编辑  收藏  举报