Golang面向對象編程之構造函數【struct&new】
- 2019 年 12 月 12 日
- 筆記
Golang面向對象編程之構造函數【struct&new】
201808
構造函數是一種特殊的方法,主要用來在創建對象時初始化對象,即為對象成員變數賦初始值。特別的一個類可以有多個構造函數 ,可根據其參數個數的不同或參數類型的不同來區分它們,即構造函數的重載。
Golang裡面沒有構造函數,但是Golang卻可以像C++一樣實現類似繼承、構造函數一樣等面向對象編程的思想和方法。Golang裡面要實現相關的構造函數定義可以通過通過new來創建構造函數。
一個簡單的構造函數的實現
定義一個結構
type ContentMsg struct { EffectId int `json:"effect_id"` Text string `json:"text"` Data interface{} `json: "data"` }
通過new一個對象,或者利用Golang本身的&方式來生成一個對象並返回一個對象指針:
unc NewContentMsg(data, effectId int) *ContentMsg { instance := new(ContentMsg) instance.Data = data instance.EffectId = effectId return instance } func NewContentMsgV2(data, effectId int) *ContentMsg { return &ContentMsg{ Data: data, EffectId: effectId, } }
更為優雅的構造的函數的實現
/* 一個更為優雅的構造函數的實現方式 參考: * 1,項目:"gitlab.xxx.com/xxx/redis" * 2,鏈接:https://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html 通過這個方式可以方便構造不同對象,同時避免了大量重複程式碼 */ package main import ( "fmt" "time" "golang.org/x/net/context" ) type Cluster struct { opts options } type options struct { connectionTimeout time.Duration readTimeout time.Duration writeTimeout time.Duration logError func(ctx context.Context, err error) } // 通過一個選項實現為一個函數指針來達到一個目的:設置選項中的數據的狀態 // Golang函數指針的用法 type Option func(c *options) // 設置某個參數的一個具體實現,用到了閉包的用法。 // 不僅僅只是設置而採用閉包的目的是為了更為優化,更好用,對用戶更友好 func LogError(f func(ctx context.Context, err error)) Option { return func(opts *options) { opts.logError = f } } func ConnectionTimeout(d time.Duration) Option { return func(opts *options) { opts.connectionTimeout = d } } func WriteTimeout(d time.Duration) Option { return func(opts *options) { opts.writeTimeout = d } } func ReadTimeout(d time.Duration) Option { return func(opts *options) { opts.readTimeout = d } } // 構造函數具體實現,傳入相關Option,new一個對象並賦值 // 如果參數很多,也不需要傳入很多參數,只需要傳入opts ...Option即可 func NewCluster(opts ...Option) *Cluster { clusterOpts := options{} for _, opt := range opts { // 函數指針的賦值調用 opt(&clusterOpts) } cluster := new(Cluster) cluster.opts = clusterOpts return cluster } func main() { // 前期儲備,設定相關參數 commonsOpts := []Option{ ConnectionTimeout(1 * time.Second), ReadTimeout(2 * time.Second), WriteTimeout(3 * time.Second), LogError(func(ctx context.Context, err error) { }), } // 終極操作,構造函數 cluster := NewCluster(commonsOpts...) // 測試驗證 fmt.Println(cluster.opts.connectionTimeout) fmt.Println(cluster.opts.writeTimeout) }