Strategy

Strategy design pattern is to encapsulate multiple algorithms under a single interface with a set of parameter flags, allowing the client to operate the same interface with different algorithm. Thus, that is the name strategy.

The idea is that the client only uses a standardized interface, passing parameter flag into it for selecting the algorithm it wanted to use at runtime. This allows the interface to strategically choose which algorithms to deploy based on the flag.

The design diagram is as follows:

When to Deploy (Problem)

  • When the problem need to have a selection of algorithms at runtime.
  • When the problem requires heavy encapsulations over multiple algorithms.
  • When the problem requires to add additional variation/choices in the future.
  • When the problem requires a standardized interface for client but undecided with the underlying implementations.

Example (Solution)

Here is an example of strategy pattern in Go:

package main

import (
  "fmt"
)

const (
        english  = 0
        mandarin = 1
        french   = 2
)

func algo1() string {
        return "Hello World"
}

func algo2() string {
        return "你好"
}

func algo3() string {
        return "Bonjour"
}

func sayHello(language int) {
        s := algo1()

        switch language {
        case 1:
                s = algo2()
        case 2:
                s = algo3()
        }

        fmt.Printf("%v\n", s)
}

func main() {
        sayHello(english)
        sayHello(mandarin)
        sayHello(french)
}

Notice that in client main, it only calls the same sayHello interfacing function only but with supply of a language flag. This allows sayHello to strategically choose with algorithm to use, with default to algo1.

Expected Outcome (Consequences)

  • Low coupling between class/modules
  • Design for reuse and long term maintainability
  • Facilitate evolutionary.
  • Encapsulate algorithms.
  • Set explicit interface.