Here's the the general problem I am trying to solve:
This seems like a perfect case for the Strategy Pattern but am not sure how best to make that work in Go.
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.
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.
@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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With