索引

https://waterflow.link/articles/1663835071801

当我在使用go-zero时,我看到了好多像下面这样的代码:

  1. ...
  2. type (
  3. // RunOption defines the method to customize a Server.
  4. RunOption func(*Server)
  5. // A Server is a http server.
  6. Server struct {
  7. ngin *engine
  8. router httpx.Router
  9. }
  10. )
  11. ...
  12. // AddRoutes add given routes into the Server.
  13. func (s *Server) AddRoutes(rs []Route, opts ...RouteOption) {
  14. r := featuredRoutes{
  15. routes: rs,
  16. }
  17. for _, opt := range opts {
  18. opt(&r)
  19. }
  20. s.ngin.addRoutes(r)
  21. }
  22. ...
  23. // WithJwt returns a func to enable jwt authentication in given route.
  24. func WithJwt(secret string) RouteOption {
  25. return func(r *featuredRoutes) {
  26. validateSecret(secret)
  27. r.jwt.enabled = true
  28. r.jwt.secret = secret
  29. }
  30. }

我们可以把重点放在RouteOption上面。这里就使用了选项模式。

什么是选项模式?

选项模式是一种函数式编程模式,用于为可用于修改其行为的函数提供可选参数。

如果你用过php的话,你肯定会看到过这样的函数,毕竟PHP是世界上最好的语言:

  1. public function cache(callable $callable, $duration = null, $dependency = null)
  2. // 我们可以这样调用
  3. cache($callable);
  4. // 也可以把后面的可选参数带上
  5. cache($callable, $duration);

这种能力在 API 设计中非常有用,因为

  • 允许用户以最低配置使用方法,同时仍为有经验的用户提供充足的配置选项。
  • 允许开发者在不破坏向后兼容性的情况下添加新选项。

然而,在 Golang 中,这是不可能的。该语言不提供添加可选参数的方法。

这就是“选项模式”的用武之地。它允许用户在调用方法 时传递其他选项,然后可以相应地修改其行为。让我们看一个小例子。

假设我们有一个结构体Server,它有 3 个属性port, timeoutmaxConnections

  1. type Server struct {
  2. port string
  3. timeout time.Duration
  4. maxConnections int
  5. }

然后我们有个Server的工厂方法

  1. func NewServer(port string, timeout time.Duration, maxConnections int) *Server {
  2. return &Server{
  3. port: port,
  4. timeout: timeout,
  5. maxConnections: maxConnections,
  6. }
  7. }

但是现在我们希望只有端口号是必传的,timeoutmaxConnections成为可选参数。在很多情况下,这些的默认值就足够了。另外,我不想用这些不必要的配置来轰炸刚刚学习或试验我的 方法 的新用户。让我们看看该怎么去实现。

首先我们定义一个新的option结构体

  1. type Option func(*Server)

Option是一个函数类型,它接受指向我们的Server. 这很重要,因为我们将使用这些选项修改我们的Server实例。

现在让我们定义我们的选项。惯例是在我们的选项前面加上 With,但可以随意选择适合您的域语言的任何名称

  1. func WithTimeout(timeout time.Duration) Option {
  2. return func(s *Server) {
  3. s.timeout = timeout
  4. }
  5. }
  6. func WithMaxConnections(maxConn int) Option {
  7. return func(s *Server) {
  8. s.maxConnections = maxConn
  9. }
  10. }

我们的两个选项WithTimeoutWithMaxConnections,采用配置值并返回一个Option。这Option只是一个函数,它接受一个指向我们Server对象的指针并将所需的属性设置为提供的值。例如,WithTimeout获取超时持续时间,然后返回一个函数(其签名与 Option相同)将我们服务器的 timeout 属性设置为提供的值。

在这里,我们使用了一种几乎所有现代语言(包括 Golang)都支持的称为闭包的技术

我们的工厂方法Server现在需要修改以支持这种变化

  1. func NewServer(port string, options ...Option) *Server {
  2. server := &Server{
  3. port: port,
  4. }
  5. for _, option := range options {
  6. option(server)
  7. }
  8. return server
  9. }

现在我们就可以用上面世界上最好的语言的方式调用了

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

在这里你可以看到我们的客户端现在可以创建一个只有端口的最小服务器,但如果需要也可以自由地提供更多的配置选项。

这种设计具有高度的可扩展性和可维护性,甚至比我们在 PHP 中看到的可选参数还要好。它允许我们添加更多选项,而不会膨胀我们的函数签名,也不会触及我们在工厂方法中的代码。

下面是完整代码:

  1. package main
  2. import "time"
  3. type Option func(*Server)
  4. type Server struct {
  5. port string
  6. timeout time.Duration
  7. maxConnections int
  8. }
  9. func NewServer(port string, options ...Option) *Server {
  10. server := &Server{
  11. port: port,
  12. }
  13. for _, option := range options {
  14. option(server)
  15. }
  16. return server
  17. }
  18. func WithTimeout(timeout time.Duration) Option {
  19. return func(s *Server) {
  20. s.timeout = timeout
  21. }
  22. }
  23. func WithMaxConnections(maxConn int) Option {
  24. return func(s *Server) {
  25. s.maxConnections = maxConn
  26. }
  27. }
  28. func main() {
  29. NewServer("8430")
  30. NewServer("8430", WithTimeout(10*time.Second))
  31. NewServer("8430", WithTimeout(10*time.Second), WithMaxConnections(10))
  32. }

golang中的选项模式的更多相关文章

  1. (13)ASP.NET Core 中的选项模式(Options)

    1.前言 选项(Options)模式是对配置(Configuration)的功能的延伸.在12章(ASP.NET Core中的配置二)Configuration中有介绍过该功能(绑定到实体类.绑定至对 ...

  2. 基于SqlSugar的开发框架循序渐进介绍(7)-- 在文件上传模块中采用选项模式【Options】处理常规上传和FTP文件上传

    在基于SqlSugar的开发框架的服务层中处理文件上传的时候,我们一般有两种处理方式,一种是常规的把文件存储在本地文件系统中,一种是通过FTP方式存储到指定的FTP服务器上.这种处理应该由程序进行配置 ...

  3. golang中逗号ok模式_转

    ,ok,第一个参数是一个值或者nil,第二个参数是true/false或者一个错误error.在一个需要赋值的if条件语句中,使用这种模式去检测第二个参数值会让代码显得优雅简洁.这种模式在go语言编码 ...

  4. asp.net core 3.0 选项模式1:使用

    本篇只是从应用角度来说明asp.net core的选项模式,下一篇会从源码来分析 1.以前的方式 以前我们使用web.config/app.config时是这样使用配置的 var count = Co ...

  5. Go语言设计模式之函数式选项模式

    Go语言设计模式之函数式选项模式 本文主要介绍了Go语言中函数式选项模式及该设计模式在实际编程中的应用. 为什么需要函数式选项模式? 最近看go-micro/options.go源码的时候,发现了一段 ...

  6. Go语言实践模式 - 函数选项模式(Functional Options Pattern)

    什么是函数选项模式 大家好,我是小白,有点黑的那个白. 最近遇到一个问题,因为业务需求,需要对接三方平台. 而三方平台提供的一些HTTP(S)接口都有统一的密钥生成规则要求. 为此我们封装了一个独立的 ...

  7. Golang 常见设计模式之选项模式

    熟悉 Python 开发的同学都知道,Python 有默认参数的存在,使得我们在实例化一个对象的时候,可以根据需要来选择性的覆盖某些默认参数,以此来决定如何实例化对象.当一个对象有多个默认参数时,这个 ...

  8. 安卓中的Model-View-Presenter模式介绍

    转载自:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0425/2782.html 英文原文:Introduction to M ...

  9. 基础知识 - Golang 中的正则表达式

    ------------------------------------------------------------ Golang中的正则表达式 ------------------------- ...

随机推荐

  1. 使用jmh框架进行benchmark测试

    性能问题 最近在跑flink社区1.15版本使用json_value函数时,发现其性能很差,通过jstack查看堆栈经常在执行以下堆栈 可以看到这里的逻辑是在等锁,查看jsonpath的LRUCach ...

  2. 深入Synchronized各种使用方法

    深入学习Synchronized各种使用方法 在Java当中synchronized通常是用来标记一个方法或者代码块.在Java当中被synchronized标记的代码或者方法在同一个时刻只能够有一个 ...

  3. 文件上传接入阿里云OSS

    目的:将文件交给阿里云进行管理,可避免文件对本地服务器资源的占用,阿里云OSS还可根据读写偏好选择合适的文件存储类型服务器,文件异地备份等 一.阿里云OSS基础了解(前提) 1.存储空间(Bucket ...

  4. python中文官方文档记录

    随笔记录 python3.10中文官方文档百度网盘链接:https://pan.baidu.com/s/18XBjPzQTrZa5MLeFkT2whw?pwd=1013 提取码:1013 1.pyth ...

  5. 论文解读(GATv2)《How Attentive are Graph Attention Networks?》

    论文信息 论文标题:How Attentive are Graph Attention Networks?论文作者:Shaked Brody, Uri Alon, Eran Yahav论文来源:202 ...

  6. 定语从句关系代词只能用 that 的情况

    当先行词被形容词最高级.序数词,以及 the only.the very.the right 等修饰时,关系代词只能用 that. This is the most interesting movie ...

  7. ipi发送阻塞导致crash

    3.10的内核, 在子进程退出的时候,发送信号通知父进程,此时是持有父进程的sighand中的spinlock的,然后父进程和该子进程不在一个核上,发送ipi的reschedule中断给对应的核, 但 ...

  8. B2. Wonderful Coloring - 2

    链接:Problem - 1551B2 - Codeforces 题意:有m个颜色,要求每种颜色内的数字各不相同,问,颜色的最大长度多少. 题解:  判断每个数字的个数,如果大于m,那么最大长度就加一 ...

  9. Pwn出题指南

    0x00:背景 最近在为社团招新赛出pwn题,发现网上关于出题方面的文章资料特别少,所以打算记录下自己出题的过程,便于网友们参考学习.本次出题采用了ctf_xinetd与pwn_deploy_chro ...

  10. http服务(postman调用方法及反参)

    #region 监听url #region 监听url路径请求 static HttpListener httpobj; private void listeningUrl() { //提供一个简单的 ...