How to Implement the Strategy Pattern in Go with Interfaces

Implement the Strategy Pattern in Go by defining an interface for algorithms and injecting concrete implementations into a context struct to swap behavior at runtime.

Implement the Strategy Pattern in Go by defining an interface for the algorithm and concrete structs that implement it, then injecting the interface into a context struct.

// Define the strategy interface
type Strategy interface {
	Execute()
}

// Concrete strategies
type ConcreteStrategyA struct{}
func (s *ConcreteStrategyA) Execute() { fmt.Println("Strategy A") }

type ConcreteStrategyB struct{}
func (s *ConcreteStrategyB) Execute() { fmt.Println("Strategy B") }

// Context using the strategy
type Context struct {
	strategy Strategy
}

func (c *Context) SetStrategy(s Strategy) { c.strategy = s }
func (c *Context) DoWork() { c.strategy.Execute() }

// Usage
ctx := &Context{}
ctx.SetStrategy(&ConcreteStrategyA{})
ctx.DoWork() // Output: Strategy A
ctx.SetStrategy(&ConcreteStrategyB{})
ctx.DoWork() // Output: Strategy B