How to implement the decorator pattern in Golang?

In the Go language, the feature of using functions as parameters and return values can be used to implement the decorator pattern.

Here is an example code demonstrating how to use the decorator pattern to add functionality to a function.

package main

import "fmt"

// 定义一个原始的函数类型
type FooFunc func()

// 原始的函数
func Foo() {
    fmt.Println("This is the original function.")
}

// 装饰器函数类型
type DecoratorFunc func(FooFunc) FooFunc

// 装饰器函数,用于在原始函数执行前后增加额外的功能
func Decorator(f FooFunc) FooFunc {
    return func() {
        fmt.Println("Before calling the original function.")
        f() // 调用原始函数
        fmt.Println("After calling the original function.")
    }
}

func main() {
    // 创建一个装饰器函数
    decoratedFoo := Decorator(Foo)
    
    // 调用装饰后的函数
    decoratedFoo()
}

When running the code above, the output will be:

Before calling the original function.
This is the original function.
After calling the original function.

In this example code, Foo is a raw function, and Decorator is a decorator function. The decorator function takes a function type as a parameter and returns a function with the same function type.

Decorator functions can add additional functionality code before and after calling the original function. In this example, the decorator function prints the message “Before calling the original function.” before calling the original function and “After calling the original function.” after calling it.

By using the decorator pattern, we can dynamically add extra functionality without modifying the original function code.

bannerAds