Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Strategy Pattern in Go?

Here's the the general problem I am trying to solve:

  1. One set of packages is collecting data from one source and sending it to many channels.
  2. A second set of packages is collecting data from many channels and writing it to one source. This set of packages would need to translate data from multiple formats.

This seems like a perfect case for the Strategy Pattern but am not sure how best to make that work in Go.

like image 874
KevDog Avatar asked Jul 22 '13 14:07

KevDog


People also ask

What is strategy pattern in Java?

Strategy design pattern is one of the behavioral design pattern. Strategy pattern is used when we have multiple algorithm for a specific task and client decides the actual implementation to be used at runtime.

What is Golang adapter?

Adapter is a structural design pattern, which allows incompatible objects to collaborate. The Adapter acts as a wrapper between two objects. It catches calls for one object and transforms them to format and interface recognizable by the second object.


2 Answers

@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.

like image 79
Dr.eel Avatar answered Oct 14 '22 23:10

Dr.eel


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.

like image 34
thwd Avatar answered Oct 14 '22 23:10

thwd