golang多参数Functional Options Pattern模式用法

调用方标题代码

package main

import (
	"demo/cmd/opt/opt"
	"fmt"
)

func main() {

	client := opt.NewClient("httpServer",
		opt.WithProtocol("https"),
		opt.WithUrl("www.baidu.com"),
		//opt.WithPort(8080),//比如这里可以不用设置端口号,实际就是默认的443
		opt.WithTimeout(10),
	)
	fmt.Printf("client:%+v", client)
	//fmt.Printf("%s\n%s\n%s\n%d\n%d\n", client.ServerName, client.Protocol, client.Url, client.Port, client.Timeout)
}

具体实现代码

package opt

type Client struct {
	ServerName string
	Url        string
	Timeout    int
	Port       int
	Protocol   string
}

type OptionsFunc func(*Client)

func NewClient(serverName string, opts ...OptionsFunc) *Client {
	client := &Client{
		ServerName: "mcp.example.com",
		Url:        "/mcp/v1/notify",
		Timeout:    10,
		Port:       443,
		Protocol:   "https",
	}
	for _, opt := range opts {
		opt(client)
	}
	return client
}

func WithUrl(url string) OptionsFunc {
	return func(client *Client) {
		client.Url = url
	}
}
func WithTimeout(timeout int) OptionsFunc {
	return func(client *Client) {
		client.Timeout = timeout
	}
}
func WithPort(port int) OptionsFunc {
	return func(client *Client) {
		client.Port = port
	}
}
func WithProtocol(protocol string) OptionsFunc {
	return func(client *Client) {
		client.Protocol = protocol
	}
}

结果

该方法适用入参过多的情况,如果参数过多,可能形参比较长

API server listening at: 127.0.0.1:60990
WARNING: undefined behavior - version of Delve is too old for Go version go1.25rc3 (maximum supported version 1.24)
client:&{ServerName:mcp.example.com Url:www.baidu.com Timeout:10 Port:443 Protocol:https}
调试器 已完成,退出代码为 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值