Photo by Jessica Ruscello

Design Patterns — Singleton

Gabriel Meireles
dev.meireles
Published in
3 min readApr 6, 2022

--

Hello there! In this article let’s talk a bit about Design Patterns, specifically regarding to Singleton. Let’s start our journey through the learning path with the Creational Design Patterns.

What is Singleton?

The Singleton is one of the Creational Design Pattern that’s part of the Gang of Four also know as GoF. This pattern ensures that a class has only an unique instance providing a global entry point, so it means, your class can only be instantiated once, exemplifying:

When use Singleton?

Taking into account that a Singleton class has an unique instance, you can consider to use it on your application that should have just a single instance of your class available, as example, a class that contains a method to connect and disconnect your code application to a database so with that you don’t need to request a new connection for every query or request; You can consider a log class that’ll persists throughout your application or even a class to initiate and persists some settings for your code, exemplifying:

The class Register has two properties, _instance and count and two methods getInstance and setCount

Line#8 — The_instance property that should be accessed only by Register class
Line#13 — The count property
Line#19 Setting the getInstance method, it’ll accessed when we need to instantiate the Register class
Line#27 setCount method that will receive a number and update the this.count value
The Singleton magic happens on line 20 on getInstance method, it’ll try to return the this._instance if it exists, otherwise it’ll create a new instance using the this() and set it as value of this._instance
Pure rocket science, isn’t?

Let’s execute the Register class to see their behavior and the step by step:

Line#4 and Line#5 — Setting s1 and s2 as Register.getInstance()
Line#7 — Comparing if the s1 and s2 are equals
Line#13 — Setting the count property of s1 instance
Line#18 — Setting the count property of s2 instance

And now let’s see the result:

So far, so good! But there’s a bit trick, if you try to instantiate the Register class using new Register() it’ll work as expected, let’s see a example:

And here the log return:

It means, we’ve a pattern break, so let’s fix it adding a private constructor the Register class:

Line#18 — The private constructor that’ll prevent the class from being instantiated using a new Register() with that you probably will get: Constructor of class ‘Register’ is private and only accessible within the class declaration.

Briefly, to have a Singleton class you need:

  • Have the constructor of the class private
  • A private static property to storing your class
  • A method to initialize and instantiate the class

--

--