Decorator function pattern in Golang


Decorator function pattern is a pattern that is mainly found in Python and JavaScript, but we can also use it in Golang.

It is a pattern in which we can add our own functionality over a current function by wrapping it. Since functions in Golang are considered firstclass objects, which in turn means that we can pass them as arguments as we would in the case of a variable.

Example 1

Let's start with a very simple example to understand the basic case of passing a function as an argument to an already existing function.

Consider the code shown below.

package main

import (
   "fmt"
   "time"
)

func printFunc() {
   fmt.Println("TutorialsPoint")
   time.Sleep(time.Second)
}

func main() {
   fmt.Printf("Data Type: %T\n", printFunc)
}

Output

If we run the command go run main.go on the above code we will get the following output in the terminal.

Data Type: func()

Example 2

The above example shows the case that we can subsequently pass the functions as arguments and now let's see a simple decorator pattern function.

Consider the code shown below.

package main

import (
   "fmt"
   "time"
)

func printFunc() {
   fmt.Println("TutorialsPoint")
   time.Sleep(1 * time.Second)
}

func coolFunc(sample func()) {
   fmt.Printf("Beginning: %s\n", time.Now())
   sample()
   fmt.Printf("Ending: %s\n", time.Now())
}

func main() {
   fmt.Printf("Data Type: %T\n", printFunc)
   coolFunc(printFunc)
}

In the above code, we have a simple decorator pattern where we have passed a function named printFunc() as an argument to the function named coolFunc() which when invoked will automatically call the printFunc() and hence the decorator pattern.

The above example shows how to effectively wrap the original function without having to alter its implementation.

Output

If we run the command go run main.go on the above code we will get the following output in the terminal.

Data Type: func()
Beginning: 2021-11-01 06:59:13.490709501 +0000 UTC
TutorialsPoint
Ending: 2021-11-01 06:59:14.490865087 +0000 UTC

Updated on: 01-Nov-2021

835 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements