Singleton In Android

Ali Talha Çoban
2 min readAug 26, 2021

Hi everyone, in this story I’ll try to explain Singleton and how you can use it in your Android applications.

What is Singleton ?

Before getting into example, we should know what singleton is. Singleton is a Design Pattern used in Android applications. Singleton is a design pattern that restricts the instantiation of a class to only one instance.

Why we should use Singleton?

Let’s assume that we have a class named DataService which keeps data of your project. So every time, whenever you want to load data, you will create a new instance of DataService class and subsequently call its method to load the required data. Maybe you can not aware absence of Singleton class, but as your project grows, you will start putting an unnecessary burden on the system memory.

How to Use Singleton In Our Projects ?

As we understand what is Singleton and why we should use it. So, It’s time to learn how to use it. We use Singleton as a class that can have private constructor and have only one object (an instance of the class) at a time. After first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created. So we avoid creating multiple object reference in this way. OK, let’s code it.

MySingleton Class;

MainActivity ;

Output;

Hashcode of data1 is 558638686
Hashcode of data2 is 558638686
Hashcode of data 3 is 558638686
Three objects point to the same memory location on the heap i.e, to the same object

Thank You for giving a read to this. Don’t forget to clap. Keep on following for such stories.

contact: cobanalitalha@gmail.com

--

--