Go语言通过函数类型与闭包实现函数级装饰器,或通过接口嵌入结构体实现接口级装饰器,支持职责单一、可组合的动态行为增强,辅以选项模式简化配置。

Go 语言没有类和继承,也不支持注解(如 Python 的 @decorator),但可以通过函数式编程和接口组合,自然、清晰地实现装饰器模式的核心思想:在不修改原始对象的前提下,动态地添加行为或责任。
装饰器本质是“包装”——把一个函数/方法包裹进另一个函数中,在调用前后插入额外逻辑。Go 中可将核心操作抽象为函数类型,再用闭包构造装饰器:
示例:日志装饰器
type Handler func(string) string
func WithLogging(h Handler) Handler {
return func(s string) string {
fmt.Println("→ 开始处理:", s)
result := h(s)
fmt.Println("← 处理完成,结果:", result)
return result
}
}
// 原始处理器
func Echo(s string) string {
return "echo: " + s
}
// 使用装饰器包装
loggedEcho := WithLogging(Echo)
loggedEcho("hello") // 输出带日志的调用过程
当需要装饰一组相关方法(如 HTTP handler、数据访问器等),推荐定义接口 + 嵌入式结构体。被装饰对象实现接口,装饰器结构体持有该接口并重写部分方法:
立即学习“go语言免费学习笔记(深入)”;
示例:HTTP Handler 装饰器链
type Service interface {
Get(id string) (string, error)
Post(data string) error
}
type RealService struct{}
func (r RealService) Get(id string) (string, error) {
return "data-" + id, nil
}
func (r RealService) Post(data string) error {
fmt.Println("保存数据:", data)
return nil
}
// 日志装饰器
type LoggingService struct {
Service // 嵌入原始服务
}
func (l LoggingService) Get(id string) (string, error) {
fmt.Printf("[LOG] GET %s\n", id)
return l.Service.Get(id)
}
// 重试装饰器(可叠加)
type RetryService struct {
Service
maxRetries int
}
func (r RetryService) Get(id string) (string, error) {
for i := 0; i <= r.maxRetries; i++ {
if i > 0 {
time.Sleep(time.Second)
}
if res, err := r.Service.Get(id); err == nil {
return res, nil
}
}
return "", fmt.Errorf("GET 失败,已重试 %d 次", r.maxRetries)
}
// 组合使用
svc := LoggingService{RealService{}}
svc = RetryService{Service: svc, maxRetries: 2}
多个装饰器参数(如超时、标签、开关)可通过函数选项统一管理,避免构造函数爆炸:
type Option func(*DecoratedService)
func WithTimeout(d time.Duration) Option {
return func(ds *DecoratedService) {
ds.timeout = d
}
}
func WithTag(tag string) Option {
return func(ds *DecoratedService) {
ds.tag = tag
}
}
type DecoratedService struct {
inner Service
timeout time.Duration
tag string
}
func NewDecoratedService(inner Service, opts ...Option) *DecoratedService {
ds := &DecoratedService{inner: inner}
for _, opt := range opts {
opt(ds)
}
return ds
}
// 使用
svc := NewDecoratedService(RealService{}, WithTimeout(5*time.Second), WithTag("api-v1"))
装饰器虽灵活,但需警惕常见陷阱:
ds.inner.Xxx() 时,确保 inner 不是自身(防无限递归)以上就是如何使用Golang实现装饰器模式_动态扩展对象功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号