Singleton Design Pattern

For this tutorial, I am using Android Studio Beta 0.8 as an IDE.

Definition:  🙁

“A design pattern that restricts the instantiation of a class to one object”.

I won’t be explaining this definition. Rather I would start with my favorite part that is called PRACTICAL EXAMPLE. After that you easily know, what is this definition saying and what is Singleton Design Pattern :).

Step 1:
Create a new Android Project and create some classes as shown below image.

New Android Project

Here we are creating an app in which user first register themselves. And after successful registration, he/she can create a task list.

In above image you see three Java classes.
1. RegisterForm.Java
2. TaskList.java
3. ValidationSimgleton.Java
Now here our main focus on  ValidationSimgleton.java class. In which I write some validation functions. So now first we see how we make any class as singleton.
Step2:
There are different coding techniques to make any class singleton. But here I only show you one of them.

SIngleton Class

Now in above image there are three headings 1,2,3. I am going to explain them to you one by one.

First: 1.

1 -> private static ValidationSingleton mSingletonObj = null;
I make a same class object which is private static. It means it is created at compile time but it is private so not available outside the class.
Second: 2.
2 -> private ValidationSingleton() { }
The key part of the singleton class. It is also a very interesting interview question. Many times some people ask you, is it possible to make constructor private? And the answer is Yes.
Now we know that in OOP the constructor is the method which is automatically called when object is created. But here we know it is private so it is clear, we cannot make this class object outside the class.
Now here we complete half definition of Singleton Pattern. Means we restrict to any one who are using your code/library to instantiate this class object. But at this time we can instantiate more than one objects of that class in its class definition, because private constructor is available on class level.
Third: 3.
a.    public static ValidationSingleton getInstance() {
b.      if (mSingletonObj == null) {
c.        mSingletonObj = new ValidationSingleton();
d.      }
e.      return mSingletonObj;
f.     }
Now here we complete the definition of singleton. But how ?
In code the getInstance() is the only method which can give you the object of this class. Now in line a, we make this method public static so its mean it is available any where in complete code with class name because it is static. In line b, we check or restrict to instantiate only one object of that class.
Now when first time getInstance() called here mSingletonObj == null is true and we make the new Object and give that object refrence to our mSingletonObj object. And after that we return this object.
Now any where of the program we again need to this class object. We again call the getInstance() but at this time condition is false, because our mSingletonObj already have reference so we return that object which is already in memory.
Now in this manner we make the SingletonObject.
Hurray 🙂 now you know how to create a Singleton object. Now next we see, how use the Singleton in our code.
Step3:
As we want to use Singleton in our code, for that I am creating some methods in this class as shown below image.

Methods define in Singleton Class.

I think methods already self explanatory. So I am going to next step.

Step4:
Now here we are creating our singleton first time.
Initialisation of Singleton Object.
Here in image where we show Red rectangle. We first time instantiate the Singleton, so here it create in Memory.
Now in below image we also see, how we use our singleton.
Use of Singleton methods.
I think it is enough. Otherwise we bore.
So now only here I show you the application first RegisterScreen image.
Working app gif image
Here when click submit button, our isEmailValid function called and give you the message.
I think we grasp the Singleton Object concept.
Code Available at: Github
Now in which situations we will use Singletons.
1. Like mostly in Java,Android or other languages where we did not get built in feature of validation. We can make a Singleton Validation class to validate, like email validation function, Any empty validation function etc.
2. Those applications in which we use GPS Sensor mostly in mobile apps. We can make the singleton object of GPS Sensor class.
3. We can make Database connection classes as Singleton. So when and where we want to create DB connection, we always use same object.
OK Guys Bye. We’ll meet again with a new Design Pattern.
Only I want you to remember one thing “A design pattern that restricts the instantiation of a class to one object” 🙂 I think now you know its mean.
Facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

6 thoughts on “Singleton Design Pattern

  1. Your style is really unique in comparison to other folks
    I’ve read stuff from. Thank you for posting when you
    have the opportunity, Guess I’ll just book mark this web site.

  2. It’s going to be ending of mine day, except before ending I am reading
    this impressive piece of writing to increase my experience.

  3. For most up-to-date information you have to visit the web and on internet I found this web
    site as a finest website for most recent updates.

Leave a Reply

Your email address will not be published. Required fields are marked *