ComponentComponentHandlerFunchttp.HandlerFuncfunc(http.ResponseWriter, *http.Request)type HandlerFunc func(string) string
func WithLogging(next HandlerFunc) HandlerFunc {
return func(s string) string {
fmt.Printf("→ calling with: %q\n", s)
result := next(s)
fmt.Printf("← result: %q\n", result)
return result
}
}
func WithUppercase(next HandlerFunc) HandlerFunc {
return func(s string) string {
return strings.ToUpper(next(s))
}
}
// 使用:
handler := WithLogging(WithUppercase(func(s string) string {
return "hello " + s
}))
fmt.Println(handler("world")) // → calling with: "world" ← result: "HELLO WORLD"
*MyServiceProcessorProcess(input string) (string, error)next ProcessorProcessnext.Process(...)type Processor interface {
Process(string) (string, error)
}
type LoggingProcessor struct {
next Processor
}
func (l *LoggingProcessor) Process(s string) (string, error) {
fmt.Printf("[LOG] start processing %q\n", s)
defer fmt.Printf("[LOG] done\n")
return l.next.Process(s)
}
type TimeoutProcessor struct {
next Processor
duration time.Duration
}
func (t *TimeoutProcessor) Process(s string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), t.duration)
defer cancel()
// 实际中需配合 channel 或 goroutine 处理超时,此处简化
return t.next.Process(s)
}
// 组装:
base := &SimpleProcessor{}
decorated := &TimeoutProcessor{
next: &LoggingProcessor{next: base},
duration: 5 * time.Second,
}
OptionBuild()func(*Builder)Build()Build()type Option func(*Builder)
type Builder struct {
processor Processor
decorators []func(Processor) Processor
}
func NewBuilder(p Processor) *Builder {
return &Builder{processor: p}
}
func WithRetry(max int) Option {
return func(b *Builder) {
b.decorators = append(b.decorators, func(next Processor) Processor {
return &RetryProcessor{next: next, max: max}
})
}
}
func (b *Builder) Build() Processor {
p := b.processor
for _, dec := range b.decorators {
p = dec(p)
}
return p
}
// 使用:
p := NewBuilder(&SimpleProcessor{}).
Apply(WithLogging()).
Apply(WithRetry(3)).
Build()
