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.

Resurrection and Adopting Golang

It’s been a while since I last posted, but better late than never!  I’ve officially adopted Go as the programming language for all my personal projects.  Started learning the language for work, but fell in love with it’s simplicity and elegant.

I recently got Go working on a Raspberry Pi 2, and will be trying to get it working with the webcam, then hopefully implement a simple image recognition algorithm (maybe to detect a red ball).  All of which will be open sourced, so stay tuned…