Strategy pattern and Observer pattern
This is part of a series to consolidate the design pattern from multiple sources to serve as a reference guide for myself
In this post, we would discuss the Strategy Pattern and Observer Pattern
Strategy Pattern
Definition
The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently of clients that use it.
UML
Example
Consider a scenario where you were to design an application representing different types of ducks for a gaming company.
Ducks are known to have only two properties fly
and quack
. Given that these behaviours are the variable components
in your system, how would abstract them? Although not the best use case for Strategy pattern, it is the one used in the
book Head First Design Patterns and helps me recollect quickly.
Observer Pattern
Definition
The observer pattern defines a one-to-many dependency between objects so that when one object changes state all of its dependents are notified and updated automatically
UML
Example
The following UML diagram represents the system built to cater the needs of a weather data company. The company has a
weather monitoring API which exposes the current temperature, humidity, pressure and guarantees to notify any change in
the state through a call-back on the measurements changed
method.
The task is to build an extendable system to incorporate different weather display needs. The company wants us to build a current conditions display, a statistics display, a forecast display and provide support for third party displays. This example again is taken from the Head First design patterns book.