设置选项对象时不可变设置器和传统设置器之间的差异

问题描述 投票:0回答:1

经过一段时间的开源项目调查后,我经常在类的设置选项中看到该模式。 (让我们说“不变方法”)

// list of possible options
type Options struct {
    Sampler sampler
    SpanKind int
}

// define an apply function. which will be called when really initialize an object
type Option func(*Options)

// for each option. Return an function to apply that specific option
func WithSpanKind(spanKind int) Option {
    return func(o *Options) {
        o.SpanKind = spanKind
    }
}

// then. we we build a new object, we just need to receive a list of option
func NewObject(options ...Option) Object {
     final := &Options{}
     // then apply each option to options
     for _, option := range options {
         option(final)
     }
     // then build an object based on the final object
}

与上述方法相比,还有另一种使用简单的getter / setter的方法。

func (o *Options) SetSpanKind(kind int) {
   o.spanKind = kind
}

// then. we we build a new object by using directly the Options object
func NewObject(option Options) Object {
}

我的问题是:这些方法之间有什么区别,以及为什么在我已阅读的许多开放源代码中第一种方法始终首选?

注:这是一些实现上述模式的开源代码。这些开放源代码由Google发起,因此也许这种模式仅特定于Google。

谢谢

go design-patterns setter
1个回答
0
投票

至少在Golang中,使用吸气剂是一种反模式。此选项模式是众所周知的。设置程序和获取程序在Golang空间中不是很常见。

此选项模式有一个很好的好处,您可以将多个选项函数传递到生成器或构造函数中,然后遍历所有传递的选项以修改此选项类型,如您的示例中所示>]

// then. we build a new object, we just need to receive a list of option
func NewObject(options ...Option) Object {
     final := &Options{}
     // then apply each option to options
     for _, option := range options {
         option(final)
     }
     // then build an object based on the final object
}

示例构造函数调用:

NewObject(optionA, optionB, optionC, optionD)

字母和二传手

https://golang.org/doc/effective_go.html#Getters

您肯定已经阅读了有效的执行指南-> https://golang.org/doc/effective_go.html

© www.soinside.com 2019 - 2024. All rights reserved.