go的option模式

go的option模式

1.函数option

把option定义为函数。

go 复制代码
package main

import "fmt"

// ServerConfig 定义服务器配置
type ServerConfig struct {
	Port    int
	Timeout int
}

// Option 定义函数选项类型
type Option func(*ServerConfig)

// WithPort 设置服务器端口
// 这是一个闭包函数
func WithPort(port int) Option {
	return func(cfg *ServerConfig) {
		cfg.Port = port
	}
}

// WithTimeout 设置超时时间
func WithTimeout(timeout int) Option {
	return func(cfg *ServerConfig) {
		cfg.Timeout = timeout
	}
}

// NewServer 创建一个新的服务器实例
// options将参数一并传入
func NewServer(options ...Option) *ServerConfig {
	cfg := &ServerConfig{
		Port:    8080,
		Timeout: 30,
	}
	for _, opt := range options {
		opt(cfg)
	}
	return cfg
}

func main() {
	// 创建服务器实例并指定选项
	server := NewServer(
		WithPort(9090),
		WithTimeout(60),
	)

	fmt.Printf("Server Port: %d, Timeout: %d\n", server.Port, server.Timeout)
}

NewServer 函数用于创建一个新的 ServerConfig 实例。它接受一个或多个 Option 类型的参数,并使用这些参数来配置 ServerConfig 的实例。

option使用场景:

对象配置:当需要创建一个对象,并且这个对象有很多可配置的属性时,使用Option模式可以避免构造函数的参数列表变得冗长和难以管理。

go 复制代码
func main() {
	c := &ServerConfig{
		Port:    9090,
		Timeout: 30,
	}
    // x记住了80
	x := WithPort(80)
    // x函数传入参数c,x函数里面能访问80
	x(c)
}

闭包的好处:

  1. 封装状态和行为:闭包可以封装函数及其相关的引用环境,将数据和行为捆绑在一起,形成一个独立的单元。这使得函数不仅仅是一个独立的执行单元,还能够保持其自己的状态,从而在后续的调用中能够持续地使用或修改这些状态。

2.接口option

把option定义为接口。

go 复制代码
package main

import "fmt"

type ServerConfig struct {
	Port    int
	Timeout int
}

type ServerOption interface {
	Apply(config *ServerConfig)
}

type Port struct {
	Value int
}

func (p Port) Apply(config *ServerConfig) {
	config.Port = p.Value
}

type Timeout struct {
	Value int
}

func (t Timeout) Apply(config *ServerConfig) {
	config.Timeout = t.Value
}

func NewServerConfig(options ...ServerOption) *ServerConfig {
	s := new(ServerConfig)
	for _, opt := range options {
		opt.Apply(s)
	}
	return s
}

func main() {
	p := Port{8080}
	t := Timeout{10}
	s := NewServerConfig(p, t)
	fmt.Println(s)
}
相关推荐
HEJOO97 分钟前
指针与结构体:C 语言进阶核心详解
c语言·开发语言·网络
乌暮11 分钟前
JVM 原理与实践:从运行时数据区到线上故障排查
java·开发语言·jvm·后端·学习·面试
miofly11 分钟前
GitHub 今日推荐|lipflow:无麦克风唇读文字输入工具
python·开源·github
寺中人12 分钟前
Xshell 完全入门指南:从安装到实战,远程连接+文件传输+会话管理全拆解
git·ssh·github·php·远程连接·xshell·运维工具
维克兜率天31 分钟前
【维克】配对交易的季节性:哪些品种适合长拿?
android·开发语言·笔记·python·算法·kotlin·量化
沫璃染墨44 分钟前
《Qt从零入门系列(十二):Qt文件操作详解——从QFile读写到QFileInfo与记事本实战》
开发语言·网络·c++·qt·交互·信号处理·文件
时间的拾荒人1 小时前
Qt 界面布局与容器控件详解:从分组框到布局管理器
开发语言·qt·面试
elseif1232 小时前
【2026 CSP-J】【逐题精讲】超详细(15道选择,3道阅读,2道完善)
java·开发语言·c++·算法·csp
智鸟科技GemeOpen开发者智能设备2 小时前
MQTT智能插座GSPM1B2 · 开发者实战指南
java·开发语言·python·物联网