gpt4 book ai didi

go - Go 中的装饰器函数

转载 作者:行者123 更新时间:2023-12-01 19:36:20 24 4
gpt4 key购买 nike

装饰器模式(函数)有many benefits :

It is very useful when a method has many orthogonal concerns... I.e., None of these concerns are related, other than that we wanna do all (or some) of them whenever we call our method. This is where the decorator pattern really helps.

By implementing the decorator pattern we subscribe to the open-closed principal. Our method is open to future extension but closed to future modification. There's a lot of groovy benefits to obeying the open-closed principle.

但是,我发现的所有示例都非常复杂(例如,使用许多中间件编写 HTTP 服务器)。这使得我很难将该原则应用到其他地方。我需要一些可以轻松尝试的东西,以便让我全神贯注。

有人能给我一个更简单的例子来最好地说明如何在 Go 中实现装饰器模式(函数)吗?

This example by Alex Alehano ,过于简单,无法投入实际使用。我需要一些可以说明这一点的东西:

func Decorate(c Decorated, ds ...Decorator) Decorated {
decorated := c
for _, decorate := range ds {
decorated = decorate(decorated)
}
return decorated
}

根据不同的选项/指令进行字符串操作,例如,向上、向下、base64等,在我看来是最好的例子,并且还添加前缀/后缀,如“This technique proves especially valuable if the decorators themselves are parameterized”。

最佳答案

首先,装饰器基本上是一个函数,它接受另一个特定类型的函数作为其参数并返回相同类型的函数。这本质上允许您创建一系列函数。所以在 Go 中它看起来像这样:

// this is the type of functions you want to decorate
type StringManipulator func(string) string

// this is your decorator.
func ToLower(m StringManipulator) StringManipulator {
return func(s string) string {
lower := strings.ToLower(s)
return m(lower)
}
}

here's a more complete example

更新:

and here's a revised example that the applying order of fn3 and fn4 are the same

关于go - Go 中的装饰器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45944781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com