go语言 装饰器模式
2020-12-13 03:13
标签:after port decorator set ora imp err make ptr go语言 装饰器模式 标签:after port decorator set ora imp err make ptr 原文地址:https://www.cnblogs.com/w3liu/p/11070960.htmlpackage 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 \n", a, b, c)
return a + b + c
}
func bar(a, b string) string {
fmt.Printf("%s, %s \n", 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!")
}
下一篇:Go数组