用函数式模拟设计模式-职责链

78 阅读1分钟

1. 定义函数(可以看做面向对象中的的只有一个方法的接口)

type F func(s string) bool

2. 定义生成职责链的方法

var chain = func(f F, n F) F {
	var next = n
	return func(s string) bool {
		if !f(s) && next != nil {
			return next(s)
		}
		return false
	}
}

3. 定义职责链

var first = chain(func(s string) bool {
	fmt.Println(s + "111111111")
	return true
}, second)

var second = chain(func(s string) bool {
	fmt.Println(s + "22222222")
	return false
}, nil)

4. 调用

first("somestring")

5. 另一个版本


type C func(s int)
type F func(s int, n C)

var chain = func(f F, n C) C {
	var next = n
	return func(s int) {
		f(s, next)
	}
}
var first = chain(func(s int, next C) {
	if s < 10 {
		fmt.Println("first")
	} else if next != nil {
		next(s)
	}
}, second)

var second = chain(func(s int, next C) {
	if s < 20 {
		fmt.Println("second")
	} else if next != nil {
		next(s)
	}
}, third)

var third = chain(func(s int, next C) {
	if s < 30 {
		fmt.Println("third")
	} else if next != nil {
		next(s)
	}
}, nil)

6. 泛型版本


type C[T any] func(s T)
type F[T any] func(s T, n C[T])

func chain[T any](f F[T], n C[T]) C[T] {
	return func(s T) {
		f(s, n)
	}
}
func firstFun[T int](s T, next C[T]) {
	if s < 10 {
		fmt.Println("first")
	} else if next != nil {
		next(s)
	}
}

var first = chain(firstFun[int], second)

func secondFun[T int](s T, next C[T]) {
	if s < 20 {
		fmt.Println("second")
	} else if next != nil {
		next(s)
	}
}

var second = chain(secondFun[int], third)

func thirdFun[T int](s T, next C[T]) {
	if s < 30 {
		fmt.Println("third")
	} else if next != nil {
		next(s)
	}
}

var third = chain(thirdFun[int], nil)