Design Patterns a Deep Dive Into…
Singleton, Part 1
Well actually before we start let’s explain what are design patterns.
Design Patterns can be broken apart into 3 categories Creational, Structural, and Behavioral. Creational is for handling Object creation mechanisms. Structural is for identifying ways to realize relationships between objects. Finally Behavioral is for handling communication between different objects.
Singleton falls under the creational pattern and provides the best way to create an object, though it has some pitfalls. This helps create an object that is easy to implement, change, test and reuse. It solves problems such as,
- How can it be ensured that a class has only one instance?
- How can the sole instance of a class be accessed easily?
- How can a class control its instantiation?
- How can the number of instances of a class be restricted?
- How can a global variable be accessed?
Singleton hides the constructor of the class and defines a public static operation that returns the sole instance of the class. This can solve problems such an instance of a User’s Session, config settings for a web app, or reducing multiple analytics in a client-side web application. It would look something like this:
However, let’s say this is your first time making this. Well maybe you need a better example then some generic code someone wrote. Maybe you need a real world example. Well let’s think about our Planet, Earth. It was initiated a long time ago and now we all have access to the resources, attributes, and functionality. We can all access the Earth and its methods but we cannot create another one. Whatever we do to this planet is done and we can all access that information but that’s it. So the code for initiating Earth could look something like….
Because of this forced limitation, Singleton breaks object-oriented design principles since it cannot be inherited from, we have no control over the creation, and it prevents dependency inject. It also does not allow for any test-driven development either since there can’t be a clean instance of a the object and mock objects cannot properly be used in tests.
Overall the usage of Singleton is powerful, but definitely for specific moments when implementing the design. It is used when you do not want to allow for a user to create more instances of sensitive or large sets of data.