Golang面向對象編程之構造函數【struct&new】

[TOC]html

Golang面向對象編程之構造函數【struct&new】

201808git

構造函數是一種特殊的方法,主要用來在建立對象時初始化對象,即爲對象成員變量賦初始值。特別的一個類能夠有多個構造函數 ,可根據其參數個數的不一樣或參數類型的不一樣來區分它們,即構造函數的重載。golang

Golang裏面沒有構造函數,可是Golang卻能夠像C++同樣實現相似繼承、構造函數同樣等面向對象編程的思想和方法。Golang裏面要實現相關的構造函數定義能夠經過經過new來建立構造函數。redis

一個簡單的構造函數的實現

定義一個結構編程

type ContentMsg struct {
	EffectId int         `json:"effect_id"`
	Text     string      `json:"text"`
	Data     interface{} `json: "data"`
}
複製代碼

經過new一個對象,或者利用Golang自己的&方式來生成一個對象並返回一個對象指針:json

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)

}


複製代碼

【"歡迎關注個人微信公衆號:Linux 服務端系統研發,後面會大力經過微信公衆號發送優質文章"】bash

個人微信公衆號
相關文章
相關標籤/搜索