GoF Design Patterns in Go: Strategy

The strategy pattern is an critical pattern for implementing dependency injections.  It allows us to declare the interface of dependencies at design-time, and make them interchangeable at run-time.  The dependency can then be mocked, making it possible to truly unit test components with dependencies.

It can be implemented in Go via interfaces.  For our example, we are going to implement a typical business logic that depends on a DB layer to persist data.  Typically, you’ll have code that may look like this:

Notice the line “db PostgreSQL”.  The DB dependency is hard-coded into the business logic.  This makes it very hard to test BusinessLogic independently.  The tight coupling also makes it harder to replace PostgreSQL with another DB implementation. Let’s replace it with an interface.

Now, instead of a concrete implementation, we define an interface “PersistanceLayer” that requres a method, “GetItemNameById”.  BusinessLogic only deals with this interface, instead of a concrete implementation.  A concrete implementation can be injected with a constructor.

This constructor creates a new instance of BusinessLogic.  It takes a concrete implementation of the PersistanceLayer interface.  For example:
In the future, we can change the DB implementation without changing a single line of code in BusinessLogic.  Here are some possible implementations of PersistanceLayer.

Leave a Reply

Your email address will not be published. Required fields are marked *