Member-only story
Example of Strategy Pattern in Golang
What is Strategy Pattern
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
- 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")
}