go语言 装饰器模式

package decorator

import (
"fmt"
"reflect"
)

func Decorator(decoPtr, fn interface{}) (err error) {
var decoratedFunc, targetFunc reflect.Value

decoratedFunc = reflect.ValueOf(decoPtr).Elem()
targetFunc = reflect.ValueOf(fn)

v := reflect.MakeFunc(targetFunc.Type(),
func(in []reflect.Value) (out []reflect.Value) {
fmt.Println("before")
out = targetFunc.Call(in)
fmt.Println("after")
return
})

decoratedFunc.Set(v)
return
}
package decorator

import (
"fmt"
"testing"
)

func foo(a, b, c int) int {
fmt.Printf("%d, %d, %d ", a, b, c)
return a + b + c
}

func bar(a, b string) string {
fmt.Printf("%s, %s ", a, b)
return a + b
}

func TestDecorator(t *testing.T) {
//type MyFoo func(int, int, int) int
//var myfoo MyFoo
//Decorator(&myfoo, foo)
//myfoo(1, 2, 3)
mybar := bar
Decorator(&mybar, bar)
mybar("hello,", "world!")

}
原文地址:https://www.cnblogs.com/w3liu/p/11070960.html