GO 函式式選項模式(Functional Options Pattern)
阿新 • • 發佈:2021-10-16
GO 函式式選項模式(Functional Options Pattern)
Option模式的優缺點
優點:
1. 支援傳遞多個引數,並且在引數個數、型別發生變化時保持相容性
2. 任意順序傳遞引數
3. 支援預設值
4. 方便拓展
缺點:
1. 增加許多function,成本增大
2. 引數不太複雜時,儘量少用
DEMO
package main import "fmt" type Client struct { Id int64 AppKey string AppSecret string } type Option func(*Client) // go函式的引數都是值傳遞 因此想要修改Client(預設值) 必須傳遞指標 func WithAppKey(appKey string) Option { return func(client *Client) { client.AppKey = appKey } } func WithAppSecret(appSecret string) Option { return func(client *Client) { client.AppSecret = appSecret } } // // NewClient // @Description 將一個函式的引數設定為可選的功能 // @param id 固定引數,也可以將所有都放進可選引數 opts 中 // @param opts // @return Client 返回 *Client 和 Client 都可以 // func NewClient(id int64, opts ...Option) Client { o := Client{ Id: id, AppKey: "key_123456", AppSecret: "secret_123456", } for _, opt := range opts { opt(&o) // go函式的引數都是值傳遞 因此想要修改Client(預設值) 必須傳遞指標 } return o } func main() { // 使用預設值 fmt.Println(NewClient(1)) // {1 key_123456 secret_123456} // 使用傳入的值 fmt.Println(NewClient(2, WithAppKey("change_key_222"))) // {2 change_key_222 secret_123456} // 不按照順序傳入 fmt.Println(NewClient(3, WithAppSecret("change_secret_333"))) // {3 key_123456 change_secret_333} fmt.Println(NewClient(4, WithAppSecret("change_secret_444"), WithAppKey("change_key_444"))) // {4 change_key_444 change_secret_444} }