
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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