go decorator example

package main

import (
	"log"
)

type Example func(value int) error
type Middle func(example Example) Example

func Decorator1(str string) Middle {
	return func(example Example) Example {
		return func(value int) error {
			log.Printf("Decorator1 str: %v, value: %v", str, value)
			return example(value)
		}
	}
}

func Decorator2(str string) Middle {
	return func(example Example) Example {
		return func(value int) error {
			log.Printf("Decorator2 str: %v, value: %v", str, value)
			return example(value)
		}
	}
}

func NewExample() Example {
	return func(value int) error {
		log.Printf("Example %v", value)
		return nil
	}
}

func main()  {
	e := NewExample()
	e = Decorator1("111")(e)
	e = Decorator2("222")(e)
	e(999)
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章