Shared State
Learn about the shared state design pattern, which is a replacement to the singleton pattern.
Rather than forcing our design to have a singleton in which only one instance is created, no matter how the object is invoked, constructed, or initialized, it is better to replicate the data across multiple instances.
The monostate pattern
The idea of the monostate pattern is that we can have many instances that are just regular objects, without having to care whether they're singletons or not (seeing as they're just objects). The good thing about this pattern is that these objects will have their information synchronized, in a completely transparent way, without us having to worry about how this works internally.
This makes this pattern a much better choice, not only for its convenience, but also because it is less error-prone, and suffers from fewer of the disadvantages of singletons (regarding their testability, creating derived classes, and so on).
We can use this pattern on many levels, depending on how much information we need to synchronize.
In its simplest form, we can assume that we only need to have one attribute to be reflected across all instances. If that is the case, the implementation is as trivial as using a class variable, and we just need to take care of providing a correct interface to update and retrieve the value of the attribute.
Example of the monostate pattern
Let's say we have an object that has to pull
a version of some code in a Git repository by the latest tag
. There might be multiple instances of this object, and when every client calls the method for fetching the code, this object will use the tag
version from its attribute. At any point, this tag
can be updated for a newer version, and we want any other instance (new or already created) to use this new branch when the fetch
operation is being called, as shown in the following code:
Get hands-on with 1400+ tech skills courses.