如何使用Golang实现装饰器+策略模式_动态扩展功能和行为

Go可通过函数类型、闭包和接口组合实现装饰器与策略模式协同:用Handler函数类型统一行为抽象,装饰器链式增强(如超时、重试),策略接口动态切换支付方式,选项模式提升可配置性。

Go 语言没有原生的装饰器语法(如 Python 的 @decorator),也不支持类继承和接口动态实现,但完全可以通过函数式编程、高阶函数、接口组合与闭包等 Go 特性,优雅地实现“装饰器 + 策略模式”的组合效果:在运行时动态包装行为、切换策略、扩展功能,且保持类型安全和低耦合。

用函数类型和闭包模拟装饰器

核心思路是把业务逻辑抽象为函数类型,再用闭包封装增强逻辑(如日志、重试、熔断),形成可链式调用的装饰器:

定义统一的行为接口(函数类型):

type Handler func(ctx context.Context, req interface{}) (interface{}, error)

编写装饰器(返回新的 Handler):

  • 日志装饰器:记录请求耗时与结果
  • 重试装饰器:失败时按策略重试(指数退避)
  • 超时装饰器:强制中断长时间执行

示例:超时装饰器

func WithTimeout(d time.Duration) func(Handler) Handler {
    return func(next Handler) Handler {
        return func(ctx context.Context, req interface{}) (interface{}, error) {
            ctx, cancel := context.WithTimeout(ctx, d)
            defer cancel()
            return next(ctx, req)
        }
    }
}

使用方式(链式装饰):

handler := WithTimeout(5 * time.Second)(
    WithRetry(3, 100*time.Millisecond)(
        HandlePayment,
    ),
)

用接口+结构体实现策略模式

定义策略接口,不同算法/行为实现该接口。运行时通过配置或上下文注入具体策略,解耦决策逻辑与执行逻辑:

type PaymentStrategy interface {
    Pay(ctx context.Context, order *Order) error
}

type AlipayStrategy struct{} func (AlipayStrategy) Pay(ctx context.Context, order Order) error { / ... / }

type WechatPayStrategy struct{} func (WechatPayStrategy) Pay(ctx context.Context, order Order) error { / ... / }

策略工厂可根据参数动态选择:

func NewPaymentStrategy(kind string) PaymentStrategy {
    switch kind {
    case "alipay": return &AlipayStrategy{}
    case "wechat": return &WechatPayStrategy{}
    default:       return &AlipayStrategy{} // fallback
    }
}

装饰器 + 策略的协同:运行时动态增强策略行为

将策略对象包装进装饰器链,让通用横切关注点(如监控、审计)自动作用于任意策略实现:

// 将策略适配为 Handler 类型
func StrategyToHandler(s PaymentStrategy) Handler {
    return func(ctx context.Context, req interface{}) (interface{}, error) {
        order, ok := req.(*Order)
        if !ok {
            return nil, errors.New("invalid request type")
        }
        return nil, s.Pay(ctx, order)
    }
}

// 动态组合:选策略 + 加装饰 func BuildPaymentHandler(strategyName string) Handler { strategy := NewPaymentStrategy(strategyName) base := StrategyToHandler(strategy) return WithTimeout(10 * time.Second)( WithMetrics("payment")( WithRecovery(base), ), ) }

这样,同一套装饰逻辑可复用于所有策略,新增支付渠道只需实现接口,无需修改装饰代码。

进阶:用选项模式(Functional Options)提升可读性

避免长参数链和嵌套装饰器调用,改用选项模式统一配置:

type HandlerOption func(*handlerConfig)

type handlerConfig struct { timeout time.Duration maxRetries int metricsName string enableRecovery bool }

func WithTimeoutOpt(d time.Duration) HandlerOption { return func(c *handlerConfig) { c.timeout = d } }

func WithMetricsOpt(name string) HandlerOption { return func(c *handlerConfig) { c.metricsName = name } }

func NewHandler(strategy PaymentStrategy, opts ...HandlerOption) Handler { cfg := &handlerConfig{timeout: 5 * time.Second} for _, opt := range opts { opt(cfg) } h := StrategyToHandler(strategy) if cfg.timeout > 0 { h = WithTimeout(cfg.timeout)(h) } if cfg.metricsName != "" { h = WithMetrics(cfg.metricsName)(h) } if cfg.enableRecovery { h = WithRecovery(h) } return h }

调用更清晰:

h := NewHandler(&WechatPayStrategy{}, 
    WithTimeoutOpt(8*time.Second),
    WithMetricsOpt("wechat_pay"),
    WithRecoveryOpt(),
)

不复杂但容易忽略:装饰器本质是“函数转换”,策略本质是“行为抽象”。Go 中二者结合的关键,在于统一抽象层(如 Handler 函数类型)和灵活的组合方式(闭包 + 接口)。只要守住“小接口、纯函数、显式依赖”三个原则,就能写出既易测又易扩的动态行为系统。