Why Design Patterns?
- Highly reusable and proven – Design patterns are reusable solutions to problems that have already been solved. This makes them less vulnerable to errors since a countless number of developers are already using it.
- Reduces code debt and size of the codebase – Design patterns are efficient solutions; therefore, they reduce the need for refactoring. Since they are efficient solutions, the number of lines of code is also considerably lesser, which reduces the size of the codebase.
- Easy to explain to peers, vast documentation – Design patterns have been in use for quite a while. Due to this, if there's ever a need to explain a solution to a peer, there is an ample number of resources available. Not just that, due to the number of resources available, it makes it easier to get started with design patterns as well.
If you see in the code snippet above, we have two instances of Singleton. It spawns off instances every time it is called, but each time it is called, we check if the instance already exists, and only if it doesn’t, do we create it. Okay that's all well and good we hear you say, but how do you actually express this? To express this, we are assigning a random ID to every instance that is created. If you check the output, you'll be able to see that both instance 1 and instance 2 have the same IDs. No matter how many instances you create, it'll be the same as the first one.
So we've seen how we can create a single instance of a type as well as multiple instances of a type based on a constructor, how about a factory? The factory pattern has a constructor for different types and takes care of object creation based on the requirement. If you relate it with the above example, imagine sending the name of the animal and the object being created for you and returned.
The factory pattern is widely used for things like notification services where there can be different notification channels being used by an application that has different object properties. Based on the selection by the user in their preferences, or the application itself, the object is created and returned for use.
Publish-Subscribe (or Observer) Pattern
The observer pattern or the publish-subscribe pattern is a widely-used messaging model as well as a design pattern. It has a publisher or the subject, which notifies the subscribers (or dependents) of any state changes through the invocation of a function. This is a vital pattern when it comes to event-driven programming. Imagine you want to update some information on a lot of objects in your application. For this, we can make all of the dependents subscribe to the subject and then make the necessary change in the subject which will then relay back to all the subscribers.