Behavioral Patterns in Go

Strategy, Observer, Iterator

Go implements behavioral patterns like Strategy, Observer, and Iterator using interfaces, functions, and channels instead of built-in classes.

Go does not enforce specific behavioral patterns like Strategy, Observer, or Iterator through built-in classes or keywords; instead, you implement them using interfaces and functions. The Strategy pattern is realized by defining an interface for the algorithm and passing implementations as function arguments, while the Observer pattern uses channels or callback functions to notify subscribers of events. The Iterator pattern is typically replaced by Go's built-in range loop over slices, maps, or custom channels that yield values sequentially.

// Strategy Pattern: Define interface and pass implementation
type Strategy interface { Execute() }
func Process(s Strategy) { s.Execute() }

// Observer Pattern: Use channels for event notification
type Observer interface { Update(msg string) }
func Notify(observers []Observer, msg string) {
    for _, o := range observers { o.Update(msg) }
}

// Iterator Pattern: Use range over a channel or slice
func Iterate(items []int) {
    for _, item := range items { fmt.Println(item) }
}