Go语言通过函数式编程实现装饰器模式,利用函数包装扩展功能而不修改原函数。首先定义统一的函数类型如type HandlerFunc func(string) string,作为装饰器的基础。接着创建日志装饰器LoggingDecorator,在调用前后打印参数和结果,实现前置与后置增强。再构建性能监控装饰器TimingDecorator,通过time.Now()记录执行耗时,用于性能分析。多个装饰器可嵌套组合,如LoggingDecorator(TimingDecorator(handler)),形成调用链,执行顺序为外层装饰器先运行逻辑,内层函数最终执行。在HTTP服务中,类似方式应用于http.HandlerFunc,例如AuthDecorator检查请求头中的Token,实现权限校验。通过http.HandleFunc("/api/data", AuthDecorator(dataHandler))注册带认证的路由。整个机制依赖闭包和高阶函数,具备类型安全与灵活性,关键在于设计一致的函数签名并分离关注点。

在Go语言中,虽然没有像Python那样的@语法糖来直接支持装饰器,但可以通过函数式编程的方式实现装饰器模式。核心思路是用函数包装另一个函数,在不修改原函数的前提下动态添加功能。
Go中常用func(http.HandlerFunc)或自定义函数类型作为装饰器的基础。通过定义统一的处理函数签名,可以链式叠加多个增强逻辑。
定义一个处理函数类型:
<pre class="brush:php;toolbar:false;">type HandlerFunc func(string) string
写一个日志装饰器:
立即学习“go语言免费学习笔记(深入)”;
<pre class="brush:php;toolbar:false;">func LoggingDecorator(h HandlerFunc) HandlerFunc {
return func(s string) string {
fmt.Printf("调用前: 参数=%s\n", s)
result := h(s)
fmt.Printf("调用后: 返回=%s\n", result)
return result
}
}
除了日志,还可以加计时功能。这类装饰器适合做性能分析。
示例代码:
<pre class="brush:php;toolbar:false;">func TimingDecorator(h HandlerFunc) HandlerFunc {
return func(s string) string {
start := time.Now()
result := h(s)
fmt.Printf("耗时: %v\n", time.Since(start))
return result
}
}
Go允许将多个装饰器嵌套使用,从而实现功能叠加。调用顺序是从外到内,执行时则从内到外。
实际用法:
<pre class="brush:php;toolbar:false;">var handler HandlerFunc = func(s string) string {
time.Sleep(100 * time.Millisecond)
return "Hello, " + s
}
<p>// 装饰两层
decorated := LoggingDecorator(TimingDecorator(handler))</p><p>// 调用
result := decorated("World")
fmt.Println(result)</p>输出会包含日志和耗时信息,说明两个增强功能都生效了。
在Web开发中,装饰器常用于权限校验、CORS、限流等横切关注点。
比如写一个身份验证装饰器:
<pre class="brush:php;toolbar:false;">func AuthDecorator(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if token == "" {
http.Error(w, "未授权", http.StatusUnauthorized)
return
}
h(w, r)
}
}
<pre class="brush:php;toolbar:false;">http.HandleFunc("/api/data", AuthDecorator(dataHandler))
基本上就这些。Go的装饰器靠函数闭包实现,灵活且类型安全,关键是设计好函数签名并合理拆分职责。
以上就是Golang如何使用装饰器模式动态增加功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号