Decorator Pattern

本文主要讨论了 Decorator Pattern 装饰器模式的 Go 实现

Decorator Pattern 装饰器

  • 装饰器模式允许动态扩展现有对象的功能,而并不改变其内部结构。
  • 装饰器提供了一种灵活的方法来扩展对象的功能

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import "fmt"

type Object func(int) int

func CalculateDecorate(o Object) Object {
return func(n int) int {
fmt.Println("Starting the execution with the integer : ", n)

result := o(n)

fmt.Println("Execution is completed with the result : ", result)

return result
}
}

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func Double(n int) int {
return n * 2
}

func Square(n int) int {
return n * n
}

func main () {
o := CalculateDecorate(Double)
o(10)

o = CalculateDecorate(Square)
o(10)
}