The "Gang of Four" (GoF) patterns are a set of 23 design patterns that were defined by four authors in their book "Design Patterns: Elements of Reusable Object-Oriented Software". The Strategy Pattern is one of the patterns defined in the book. In this article, we will discuss how to implement the Strategy Pattern in Golang.
What is the Strategy Pattern?
The Strategy Pattern is a behavioral design pattern that enables selecting an algorithm at runtime. This pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. The pattern lets the algorithm vary independently from the clients that use it.
Implement the Strategy Pattern
To implement the Strategy Pattern in Golang, we need to define an interface that declares the algorithm's methods. We then implement the interface for each algorithm we want to use. Finally, we define a context struct that has a field of the interface type. This context struct executes the algorithm's methods through the interface's field.
Here's an example of implementing the Strategy Pattern for sorting algorithms:
package main
import (
"fmt"
)
type Sorter interface {
Sort([]int) []int
}
type BubbleSort struct{}
func (bs *BubbleSort) Sort(arr []int) []int {
// Bubble Sort implementation
return arr
}
type InsertionSort struct{}
func (is *InsertionSort) Sort(arr []int) []int {
// Insertion Sort implementation
return arr
}
type Context struct {
sorter Sorter
}
func (c *Context) SetSorter(sorter Sorter) {
c.sorter = sorter
}
func (c *Context) ExecuteSort(arr []int) []int {
return c.sorter.Sort(arr)
}
func main() {
arr := []int{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}
bubbleSort := &BubbleSort{}
insertionSort := &InsertionSort{}
context := &Context{}
context.SetSorter(bubbleSort)
fmt.Println("Bubble Sort:", context.ExecuteSort(arr))
context.SetSorter(insertionSort)
fmt.Println("Insertion Sort:", context.ExecuteSort(arr))
}
In the above code, we defined the Sorter
interface that declares the Sort
method. We then implemented the BubbleSort
and InsertionSort
structs, which implement the Sorter
interface. Finally, we defined the Context
struct, which has a field of the Sorter
interface type. The Context
struct executes the Sort
method through the interface's field.
We then created instances of the BubbleSort
and InsertionSort
structs and set them as the Context
struct's Sorter
field. Finally, we called the ExecuteSort
method on the Context
struct to execute the sort method through the Sorter
interface.
Conclusion
The Strategy Pattern is a useful pattern for selecting an algorithm at runtime. In this article, we discussed how to implement the Strategy Pattern in Golang. We also provided a code example to demonstrate how to implement the pattern.
References
- “Design Patterns: Elements of Reusable Object-Oriented Software” by Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm