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:
First In , First Out (FIFO) - remove an entry from in memory cache , that was created first.
Least Recently Used (LRU) - remove an entry from in memory cache, that has been used least recently
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
fifo.go: Strategy
lru.go: Strategy
lfu.go: Strategy
cache.go: Context
Here as you can see , the original context object(cache) holds a reference to a strategy interface(evictionAlgo).
main.go: Client Code
Output:
Evicting by lfu strtegy
Evicting by lru strtegy
Evicting by fifo strtegy
Top comments (2)
Hi, how do you generate these pictures of your code?
carbon.now.sh/