1 回答

TA貢獻1863條經(jīng)驗 獲得超2個贊
我重寫了你的例子來說明。
嵌套函數(shù)調(diào)用從內(nèi)到外執(zhí)行。每個函數(shù)調(diào)用返回一個函數(shù)。最終變量m被賦值,其結(jié)果AppendDecorator本身就是一個由所有裝飾器組成的函數(shù),看起來像這樣:
m := func(s string) string {
return ("DECORATED " + strings.ToLower(s + " GOLANG"))
}
當(dāng)我們執(zhí)行m(s)(內(nèi)部fmt.Println(m(s))時,我們正在執(zhí)行由返回的函數(shù)AppendDecorator。此函數(shù)調(diào)用m(s + x)where mis 返回的函數(shù)ToLower。當(dāng)這個函數(shù)執(zhí)行時,它調(diào)用m(lower)where is where mis the function by 返回PrependDecorator。當(dāng)這個函數(shù)執(zhí)行時,它會調(diào)用m(x + s)我們m傳入的 Identity 函數(shù)。
package main
import (
"fmt"
"strings"
)
// StringManipulator manipulate a string
type StringManipulator func(str string) string
// Identity a string manipulator that leaves the string unchanged
func Identity(s string) string {
fmt.Println("Executing Identity manipulator")
return s
}
// ToLower a lower case string manipulator
func ToLower(m StringManipulator) StringManipulator {
fmt.Println("Returning ToLower manipulator")
return func(s string) string {
fmt.Println("Executing ToLower manipulator")
lower := strings.ToLower(s)
return m(lower)
}
}
// AppendDecorator append a string manipulator
func AppendDecorator(x string, m StringManipulator) StringManipulator {
fmt.Println("Returning Append manipulator")
return func(s string) string {
fmt.Println("Executing Append manipulator")
return m(s + x)
}
}
// PrependDecorator prepend a string manipulator
func PrependDecorator(x string, m StringManipulator) StringManipulator {
fmt.Println("Returning Prepend manipulator")
return func(s string) string {
fmt.Println("Executing Prepend manipulator")
return m(x + s)
}
}
func main() {
s := "Some_String"
m := AppendDecorator(" GOLANG", ToLower(PrependDecorator("DECORATED ", Identity)))
fmt.Println(m(s))
}
來自的輸出m := AppendDecorator(" GOLANG", ToLower(PrependDecorator("DECORATED ", Identity)))是:
Returning Prepend manipulator
Returning ToLower manipulator
Returning Append manipulator
輸出fmt.Println(m(s))是:
Executing Append manipulator
Executing ToLower manipulator
Executing Prepend manipulator
Executing Identity manipulator
DECORATED some_string golang
- 1 回答
- 0 關(guān)注
- 170 瀏覽
添加回答
舉報