Example of Strategy Pattern in Golang

What is Strategy Pattern

Simplify Complexity
1 min readMay 8, 2022

--

The strategy is a behavior pattern. It fits where multiple choices for an interface are available and the design would allow switching them dynamically.

Conditions

  • A set of choices with similarities in the interface
  • Dynamic update of a choice

Example

  1. A cache with evictions
  • Multiple eviction algorithms
  • A cache could switch to a different algorithm dynamically

2. A duck type has a variety of flying behaviors. A duck can fly very fast, slow, and no-fly.

Implementation

Define what a duck is.

// duck_type.go

package maintype duck struct {
flyBehavior
}

Define fly behavior

// fly_behavior.go

package maintype flyBehavior interface {
fly()
nofly()
}

Define the fast duck fly behavior

//fast_duck.go

package mainimport "fmt"type duckF18 struct {
}
func (d *duckF18) fly() {
fmt.Printf("%+v\n", "flying like a F18")
}
func (d *duckF18) nofly() {
fmt.Printf("%+v\n", "not implemented")
}

Define no-fly behavior

// nofly_duck.go

package mainimport "fmt"type duckNofly struct {
}
func (d *duckNofly) fly() {
fmt.Printf("%+v\n", "not implemented")
}
func (d *duckNofly) nofly() {
fmt.Printf("%+v\n", "no flying")
}

// main.go

package mainfunc createNewDuck(f flyBehavior) *duck {
return &duck{
flyBehavior: f,
}
}
func (d *duck) setFlyBehavior(f flyBehavior) {
d.flyBehavior = f
}
func main() {
// f18 duck
aDuck := createNewDuck(&duckF18{})
aDuck.flyBehavior.fly()
// duck switches to no fly
aDuck.setFlyBehavior(&duckNofly{})
aDuck.flyBehavior.fly()
}

References

  1. https://golangbyexample.com/strategy-design-pattern-golang/
  2. https://www.youtube.com/watch?v=9uDFHTWCKkQ

--

--

Simplify Complexity

Golang, Distributed Systems, File Systems, Python, C/C++, Linux