Go语言中通过接口组合和函数包装实现装饰器模式,用于日志、监控等功能扩展。首先定义UserService接口及其实现,接着创建loggingDecorator和metricsDecorator结构体,分别实现调用前后的日志记录与耗时统计。通过NewLoggingDecorator和NewMetricsDecorator逐层包装服务实例,形成责任链。装饰顺序影响执行流程,如先日志后指标,则日志不包含耗时本身时间。此外,可采用函数式装饰器,利用UserFunc类型和WithLogging、WithMetrics高阶函数实现更灵活的轻量级装饰,适用于中间件场景。最终通过组合方式实现关注点分离,提升代码可维护性。

在 Go 语言中,装饰器模式通常通过函数包装或接口组合的方式来实现功能扩展,而不改变原有结构的代码。它广泛应用于日志记录、权限校验、缓存、监控等场景。下面通过一个清晰的示例展示如何使用装饰器模式为服务添加日志和耗时统计功能。
假设我们有一个用户服务,提供获取用户信息的方法:
<strong>type UserService interface {
GetUser(id int) string
}</strong>
<strong>type userService struct{}</strong>
<strong>func (s *userService) GetUser(id int) string {
fmt.Printf("Fetching user with ID: %d\n", id)
return fmt.Sprintf("User-%d", id)
}</strong>
我们可以定义一个装饰器结构体,它内部持有 UserService 接口实例,从而可以在调用前后插入额外逻辑:
<strong>type loggingDecorator struct {
service UserService
}</strong>
<strong>func NewLoggingDecorator(service UserService) UserService {
return &loggingDecorator{service: service}
}</strong>
<strong>func (d *loggingDecorator) GetUser(id int) string {
fmt.Printf("[LOG] Getting user with ID: %d\n", id)
result := d.service.GetUser(id)
fmt.Printf("[LOG] Got result: %s\n", result)
return result
}</strong>
再封装一个统计执行时间的装饰器:
立即学习“go语言免费学习笔记(深入)”;
<strong>type metricsDecorator struct {
service UserService
}</strong>
<strong>func NewMetricsDecorator(service UserService) UserService {
return &metricsDecorator{service: service}
}</strong>
<strong>func (d *metricsDecorator) GetUser(id int) string {
start := time.Now()
result := d.service.GetUser(id)
elapsed := time.Since(start)
fmt.Printf("[METRICS] GetUser(%d) took %v\n", id, elapsed)
return result
}</strong>
Go 支持将多个装饰器逐层包装,形成责任链式的处理流程:
<strong>func main() {
var service UserService = &userService{}
// 装饰:先加日志,再加指标
service = NewLoggingDecorator(service)
service = NewMetricsDecorator(service)
// 调用方法
service.GetUser(42)
}</strong>
输出结果类似:
[LOG] Getting user with ID: 42 Fetching user with ID: 42 [LOG] Got result: User-42 [METRICS] GetUser(42) took 12.5µs
注意装饰顺序会影响执行流程。如果交换装饰器顺序,日志将不包含耗时打印本身的时间。
对于更轻量的场景,可以使用函数式方式实现装饰器:
<strong>type UserFunc func(int) string</strong>
<strong>func (f UserFunc) GetUser(id int) string {
return f(id)
}</strong>
<strong>func WithLogging(fn UserFunc) UserFunc {
return func(id int) string {
fmt.Printf("[LOG] Call GetUser(%d)\n", id)
result := fn(id)
fmt.Printf("[LOG] Result: %s\n", result)
return result
}
}</strong>
<strong>func WithMetrics(fn UserFunc) UserFunc {
return func(id int) string {
start := time.Now()
result := fn(id)
fmt.Printf("[METRICS] Took %v\n", time.Since(start))
return result
}
}</strong>
使用方式:
<strong>var getUser UserFunc = func(id int) string {
return fmt.Sprintf("User-%d", id)
}
getUser = WithLogging(WithMetrics(getUser))
getUser(42)</strong>
这种方式更灵活,适合中间件类逻辑,如 HTTP 处理器链。
基本上就这些。Go 没有泛型装饰器语法糖,但通过接口和组合能自然实现装饰器模式,干净地分离关注点,提升代码可维护性。
以上就是Golang Decorator装饰器模式功能扩展示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号