Easy-Go-Web3
知识图谱Go 教程React Web3智能合约
需求分析系统设计设计模式Go 微服务
项目实战DevOps
Go 生态React 生态智能合约生态Web3 生态AI × Web3工具箱Web3 公司远程Web3求职
🎯 AA 工程师面试手册博客
GitHub
返回设计模式
创建型

函数选项模式

Go 特有的模式,使用函数参数实现灵活的配置。

问题场景

构造函数参数过多,且大部分有默认值。

解决方案

定义 Option 函数类型,通过变长参数传递配置。

Go 实现

functional-options.go
go
1type Server struct {
2 host string
3 port int
4 timeout time.Duration
5 tls bool
6}
7
8type Option func(*Server)
9
10func WithPort(port int) Option {
11 return func(s *Server) { s.port = port }
12}
13
14func WithTimeout(d time.Duration) Option {
15 return func(s *Server) { s.timeout = d }
16}
17
18func WithTLS() Option {
19 return func(s *Server) { s.tls = true }
20}
21
22func NewServer(host string, opts ...Option) *Server {
23 s := &Server{
24 host: host,
25 port: 8080, // 默认值
26 timeout: 30 * time.Second,
27 }
28 for _, opt := range opts {
29 opt(s)
30 }
31 return s
32}
33
34// 使用
35server := NewServer("0.0.0.0",
36 WithPort(3000),
37 WithTimeout(time.Minute),
38 WithTLS(),
39)

Web3 应用场景

配置 Web3 服务,如 RPC 端点、超时、重试策略等。

优点

  • +可读性强
  • +向后兼容
  • +灵活配置

缺点

  • -Option 函数较多时管理复杂
工厂模式中间件模式
Easy-Go-Web3

构建 Go 后端与 Web3 的学习之路。从基础到进阶,从理论到实践,助你成为全栈区块链开发者。

学习路径

  • 知识图谱
  • Go 教程
  • Go 微服务
  • 面试手册

资源中心

  • 工具箱
  • DevOps 工具
  • Web3 生态
  • 博客

© 2025 Easy-Go-Web3. All rights reserved.

Created withbyhardybao