欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

golang中的選項(xiàng)模式

索引

徐匯ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)建站的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18980820575(備注:SSL證書合作)期待與您的合作!

https://waterflow.link/articles/

當(dāng)我在使用go-zero時,我看到了好多像下面這樣的代碼:

...

type (
	// RunOption defines the method to customize a Server.
	RunOption func(*Server)

	// A Server is a http server.
	Server struct {
		ngin   *engine
		router httpx.Router
	}
)

...

// AddRoutes add given routes into the Server.
func (s *Server) AddRoutes(rs []Route, opts ...RouteOption) {
	r := featuredRoutes{
		routes: rs,
	}
	for _, opt := range opts {
		opt(&r)
	}
	s.ngin.addRoutes(r)
}

...

// WithJwt returns a func to enable jwt authentication in given route.
func WithJwt(secret string) RouteOption {
	return func(r *featuredRoutes) {
		validateSecret(secret)
		r.jwt.enabled = true
		r.jwt.secret = secret
	}
}

我們可以把重點(diǎn)放在RouteOption上面。這里就使用了選項(xiàng)模式。

什么是選項(xiàng)模式?

選項(xiàng)模式是一種函數(shù)式編程模式,用于為可用于修改其行為的函數(shù)提供可選參數(shù)。

如果你用過php的話,你肯定會看到過這樣的函數(shù),畢竟PHP是世界上最好的語言:

public function cache(callable $callable, $duration = null, $dependency = null)
  
// 我們可以這樣調(diào)用
cache($callable);

// 也可以把后面的可選參數(shù)帶上
cache($callable, $duration);

這種能力在 API 設(shè)計中非常有用,因?yàn)?/p>

  • 允許用戶以最低配置使用方法,同時仍為有經(jīng)驗(yàn)的用戶提供充足的配置選項(xiàng)。
  • 允許開發(fā)者在不破壞向后兼容性的情況下添加新選項(xiàng)。

然而,在 Golang 中,這是不可能的。該語言不提供添加可選參數(shù)的方法。

這就是“選項(xiàng)模式”的用武之地。它允許用戶在調(diào)用方法 時傳遞其他選項(xiàng),然后可以相應(yīng)地修改其行為。讓我們看一個小例子。

假設(shè)我們有一個結(jié)構(gòu)體Server,它有 3 個屬性port, timeoutmaxConnections

type Server struct {
	port           string
	timeout        time.Duration
	maxConnections int
}

然后我們有個Server的工廠方法

func NewServer(port string, timeout time.Duration, maxConnections int) *Server {
	return &Server{
		port:           port,
		timeout:        timeout,
		maxConnections: maxConnections,
	}
}

但是現(xiàn)在我們希望只有端口號是必傳的,timeoutmaxConnections成為可選參數(shù)。在很多情況下,這些的默認(rèn)值就足夠了。另外,我不想用這些不必要的配置來轟炸剛剛學(xué)習(xí)或試驗(yàn)我的 方法 的新用戶。讓我們看看該怎么去實(shí)現(xiàn)。

首先我們定義一個新的option結(jié)構(gòu)體

type Option func(*Server)

Option是一個函數(shù)類型,它接受指向我們的Server. 這很重要,因?yàn)槲覀儗⑹褂眠@些選項(xiàng)修改我們的Server實(shí)例。

現(xiàn)在讓我們定義我們的選項(xiàng)。慣例是在我們的選項(xiàng)前面加上 With,但可以隨意選擇適合您的域語言的任何名稱

func WithTimeout(timeout time.Duration) Option {
	return func(s *Server) {
		s.timeout = timeout
	}
}

func WithMaxConnections(maxConn int) Option {
	return func(s *Server) {
		s.maxConnections = maxConn
	}
}

我們的兩個選項(xiàng)WithTimeoutWithMaxConnections,采用配置值并返回一個Option。這Option只是一個函數(shù),它接受一個指向我們Server對象的指針并將所需的屬性設(shè)置為提供的值。例如,WithTimeout獲取超時持續(xù)時間,然后返回一個函數(shù)(其簽名與 Option相同)將我們服務(wù)器的 timeout 屬性設(shè)置為提供的值。

在這里,我們使用了一種幾乎所有現(xiàn)代語言(包括 Golang)都支持的稱為閉包的技術(shù)

我們的工廠方法Server現(xiàn)在需要修改以支持這種變化

func NewServer(port string, options ...Option) *Server {
	server := &Server{
		port: port,
	}

	for _, option := range options {
		option(server)
	}

	return server
}

現(xiàn)在我們就可以用上面世界上最好的語言的方式調(diào)用了

NewServer("8430")
NewServer("8430", WithTimeout(10*time.Second))
NewServer("8430", WithTimeout(10*time.Second), WithMaxConnections(10))

在這里你可以看到我們的客戶端現(xiàn)在可以創(chuàng)建一個只有端口的最小服務(wù)器,但如果需要也可以自由地提供更多的配置選項(xiàng)。

這種設(shè)計具有高度的可擴(kuò)展性和可維護(hù)性,甚至比我們在 PHP 中看到的可選參數(shù)還要好。它允許我們添加更多選項(xiàng),而不會膨脹我們的函數(shù)簽名,也不會觸及我們在工廠方法中的代碼。

下面是完整代碼:

package main

import "time"

type Option func(*Server)

type Server struct {
	port           string
	timeout        time.Duration
	maxConnections int
}

func NewServer(port string, options ...Option) *Server {
	server := &Server{
		port: port,
	}

	for _, option := range options {
		option(server)
	}

	return server
}

func WithTimeout(timeout time.Duration) Option {
	return func(s *Server) {
		s.timeout = timeout
	}
}

func WithMaxConnections(maxConn int) Option {
	return func(s *Server) {
		s.maxConnections = maxConn
	}
}

func main() {
	NewServer("8430")
	NewServer("8430", WithTimeout(10*time.Second))
	NewServer("8430", WithTimeout(10*time.Second), WithMaxConnections(10))
}

網(wǎng)站欄目:golang中的選項(xiàng)模式
網(wǎng)頁URL:http://chinadenli.net/article2/dsoicoc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供域名注冊、微信小程序靜態(tài)網(wǎng)站、微信公眾號、建站公司網(wǎng)站內(nèi)鏈

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

綿陽服務(wù)器托管