How to implement Strategy Pattern in Go?

In general; don't get lost in patterns and protocols to build Go applications. The language makes it easy to be expressive and straightforward. Most of the time defining solid interfaces makes everything flexible enough.

Still, here's an example of the strategy pattern in Go:

Define an interface for the behavior of the strategies:

type PackageHandlingStrategy interface {
    DoThis()
    DoThat()
}

Implement that strategy:

type SomePackageHandlingStrategy struct {
    // ...
}

func (s *SomePackageHandlingStrategy) DoThis() {
    // ...
}

func (s *SomePackageHandlingStrategy) DoThat() {
    // ...
}

And then, either embed…

type PackageWorker struct {
    SomePackageHandlingStrategy
}

func (w *PackageWorker) Work() {
    w.DoThis()
    w.DoThat()
}

…or pass the strategy…

type PackageWorker struct {}

func (w *PackageWorker) Work(s PackageHandlingStrategy) {
    s.DoThis()
    s.DoThat()
}

… to your worker.


@madhan You can make a factory of strategies. Then pass the strategy name from the config, the factory will create the instance of the strategy you need. Factory can be implemented with switch or map[string]Strateger.