DEV Community

Cover image for Strategy Design Pattern in Go
Rahul sawra
Rahul sawra

Posted on

Strategy Design Pattern in Go

According to Wikipedia,

The strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use

The strategy design pattern comes under the behavioural pattern.
Strategy design pattern turns a set of behaviors(strategies) into objects and makes them interchangable inside original context object.
We create objects which represent various strategies and a context object(original object),which holds a reference to a strategy object and delegates it executing the behaviour.
In order to change the context object perform its work, other objects may replace the currently linked strategy object with another one.

Example

Suppose we are building an in-memory cache.Since, the size of an im-memory cache is limited, whenever it reaches its maximum size alloted, some enteries have to be removed in order to free up the space. This task can happen via several algorithms:

  1. First In , First Out (FIFO) - remove an entry from in memory cache , that was created first.

  2. Least Recently Used (LRU) - remove an entry from in memory cache, that has been used least recently

  3. Least Frequently Used (LFU) - remove an entry from in memory cache, that has been used least frequently

The main idea is to decouple the cache object/class from these algorithms (strategies) so that we can change the algorithm at runtime.

Also, the original cache class should not change when a new algorithm is being added in the future.

This is where Strategy Pattern comes into play. It basically suggests to create the family of algorithms and each algorithm having its own class. Each of these classes implement the same interface and this way the algorithm becomes interchangable within the family.

Lets say the common interface name is evictionAlgo
evictionAlgo.go: Strategy Interface

Strategy Interface

fifo.go: Strategy

fifo.go

lru.go: Strategy

lru.go

lfu.go: Strategy

lfu.go

cache.go: Context

cache context object
Here as you can see , the original context object(cache) holds a reference to a strategy interface(evictionAlgo).

main.go: Client Code

main.go

Output:

Evicting by lfu strtegy
Evicting by lru strtegy
Evicting by fifo strtegy
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
davidkroell profile image
David Kröll

Hi, how do you generate these pictures of your code?

Collapse
 
im_rsawra profile image
Rahul sawra