The schema definition

Define a set of algorithms, encapsulate them, and make them interchangeable (variable). This pattern allows the algorithm to vary (extend, subclass) independently of the client that uses it (stable).

The class diagram

The point to summarize

  • Strategy and its subclasses provide components with a set of reusable algorithms that make it easy to swap types between algorithms at run time as needed
  • The Strategy pattern provides an alternative to conditional statements. Eliminating conditional statements is decoupling. Code that contains a lot of conditional determination statements typically requires the Strategy pattern
  • If the Strategy object does not have instance variables, then each context can share a Strategy object, thus saving object overhead

Go language code implementation

Project directory



strategy.go

Package Strategy // Type Strategy interface {Execute()}

strategyA.go

Package Strategy import "FMT" // A type Strategya struct {} // Func (S * Strategya) Execute(){FMT.Println("A plan Executed.")} // Simple Factory Method Func NewStrategya () Strategy {return & Strategya {}}

strategyB.go

Package Strategy import "FMT" // B type StrategyB struct {} // Func (S * StrategyB) Execute() {FMT.Println("B plan ") Executed.")} // Simple Factory Method Func NewStrategyB() Strategy {return & StrategyB {}}

context.go

Package Strategy // context, // Func newContext () *Context {return &Context{}} // Polymorphic setting specific object Func (c *Context) setStrategy (strategy strategy){c *Context setStrategy (strategy strategy); c.strategy.Execute() }

strategy_test.go

package Strategy import "testing" func TestContext_Execute(t *testing.T) { strategyA := NewStrategyA() c := NewContext()  c.SetStrategy(strategyA) c.Execute() strategyB := NewStrategyB() c.SetStrategy(strategyB) c.Execute() }