Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top