Go中的装饰器功能 [英] Decorator functions in Go

查看:202
本文介绍了Go中的装饰器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

装饰器模式(功能)具有许多好处:

Decorator pattern (functions) has 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服务器).这使我很难在其他地方应用该原则.我需要可以轻松尝试的东西,以便将我的头缠住它.

However, all the examples that I found are really complicated (e.g., writing HTTP servers with many middlewares). This make it difficult for me to apply the principle elsewhere. I need something that I can easily try on so as to wrap my head around it.

有人可以给我一个简单的例子,最好地说明如何在Go中做Decorator模式(功能)吗?

Can someone give me an simpler example that can best illustrate how to do Decorator pattern (functions) in Go please?

Alex Alehano的这个示例太简单了,无法投入实际使用.我需要一些可以说明这一点的东西:

This example by Alex Alehano, is too simple to be put into practical use. I need something that can illustrate this:

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

根据不同的选项/指令(例如,上,下,base64等)进行字符串操作将是IMO的最佳示例,并且还要添加前缀/后缀,例如"

A string manipulation according to different option/instruction, e.g., to upper, to lower, to base64, etc, would be the best example IMO, and adding prefix/suffix too, as "This technique proves especially valuable if the decorators themselves are parameterized".

推荐答案

首先,装饰器基本上是一个函数,该函数将特定类型的另一个函数作为其参数,并返回相同类型的函数.从本质上讲,这使您可以创建功能链.所以在Go中看起来像这样:

First of all, a decorator is basically a function that takes another function of a specific type as its argument and returns a function of the a same type. This essentially allows you to create a chain of functions. So in Go it would look something like this:

// 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)
    }
}

这是一个更完整的示例

这篇关于Go中的装饰器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆