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)
}
相关推荐
闪电悠米4 分钟前
黑马点评-秒杀优化-02_lua_precheck
开发语言·redis·分布式·缓存·junit·wpf·lua
盈建云系统5 分钟前
外贸网站SEO怎么做?从产品关键词到询盘页面,独立站内容优化流程和费用参考
开发语言·网站搭建
Dream_ksw10 分钟前
Python多继承之super()继承问题解决
开发语言·python
C++ 老炮儿的技术栈13 分钟前
如何利用 OpenCV 将图像显示在对话框窗口上
c语言·c++·人工智能·qt·opencv·计算机视觉·github
迈巴赫车主17 分钟前
蓝桥杯21241灯塔java
java·开发语言·数据结构·算法·职场和发展·蓝桥杯·动态规划
半个烧饼不加肉22 分钟前
JS 底层探究-- 调用栈(Call Stack)
开发语言·前端·javascript
弹简特34 分钟前
【Java项目-轻聊】08-用户管理模块-实现获取用户信息+头像上传+显示头像
java·开发语言·springboot
vickycheung339 分钟前
RK182X 如何在 RK3588 上进行应用测试
开发语言·php
半壶清水1 小时前
用python脚本加html自建的书法字典
开发语言·python·html
凯瑟琳.奥古斯特1 小时前
力扣1003题C++解法详解
开发语言·c++·算法·leetcode·职场和发展