GO语言函数不支持默认参数,想要支持默认参数,必须自己实现,但是想要实现优雅的传参模式,就要用到设计模式;以下使用Builder和Option设计模式来实现优雅的默认参数和传参。
函数Option模式
- 创建OptionRedis结构体,Id为必须要指定的尝试,Option为默认参数结构体
- 创建更改默认参数函数ModOption,便于修改默认参数
- 创建每个默认参数修改的函数SetAddr,SetDb,SetPass
- 构建初始化函数NewOptionRedis,指定默认参数的默认值,遍历加载修改默认参数的函数,以接受调用者更改后的参数,返回OptionRedis结构体
1 | package redis |
创建型Builder模式
- 创建BuilderRedis结构体
- 初始化BuilderRedis结构体NewBuilderRedis
- 分别创建修改默认参数的方法
1 | package redis |
main包调用
1 | package main |
总结
Option模式和Builder模式都能构建容易维护的默认参数代码,但是从代码结构上看,个人觉得Builder 更易懂,更清晰,调用时使用类似链式写法调用,并不符合之前在Python语言类的默认参数函数调用方法,而Option符合Python语言中默认参数函数的调用方法,但代码和Builder比较起来相对复杂。
- 本文作者: ChuLinx
- 本文链接: http://yoursite.com/2019/12/09/浅谈利用Golang的Builder&Option设计模式来传递初始化参数/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!