装饰器
装饰器结构模式允许动态地扩展现有对象的功能,而不改变其内部结构。
装饰器提供了一种灵活的方法来扩展对象的功能。
golang 实现
下面的LogDecorate用signature func(int)int修饰函数,该函数操作整数并添加输入/输出日志记录功能。
1 2 3 4 5 6 7 8 9 10 11 12 13
| type Object func(int) int
func LogDecorate(fn Object) Object { return func(n int) int { log.Println("Starting the execution with the integer", n)
result := fn(n)
log.Println("Execution is completed with the result", result)
return result } }
|
如何使用
1 2 3 4 5 6 7
| func Double(n int) int { return n*2 } f := LogDecorate(Double) f(5)
|
经验
与适配器模式不同,要修饰的对象是通过注入获得的。
装饰器不应更改对象的接口。