Are you an Android Developer and not using Singleton Class yet?
Being a developer, somewhere down the line, We still don’t use this scalable and reusable technique for our applications and program.
Singleton class is one of the creational patterns in the aspect of “Design Pattern”.
It’s a fancy word which sounds good to the interviewer and developer, only when it has been asked in the interview process.
It is very famous in the developer community but most of the developers have no idea about “why”, “how effectively” and “where” to use it.
Why should we use it?
Being a developer, We ended up creating multiple objects of one class. When we create one object it creates a memory in the system.
Let’s say We are creating 10 objects of the same class, 4 in one activity and other 6 in another activity. It will use 10 memory location for 10 objects and this will eat memory of your application or program
How effectively we can use it?
I will explain how can we use it in Android Application using both of the languages. i.e Java, Kotlin
In Java
You need to create “private constructor” and “instance” of the model class as follows
public class Coin {
private static final int ADD_MORE_COIN = 10;
private int coin;
private static Coin instance = new Coin(); // Eagerly Loading of single ton instance
private Coin(){
// private to prevent anyone else from instantiating
}
public static Coin getInstance(){
return instance;
}
public int getCoin(){
return coin;
}
public void addMoreCoin(){
coin += ADD_MORE_COIN;
}
public void deductCoin(){
coin--;
}
}
In Kotlin
It is just the “object” keyword does all the related work for us.
No need to create “private constructor” or any “instance” in a particular model class
object Coin{
private var coin: Int = 0
fun getCoin():Int{
return coin
}
fun addCoin(){
coin += 10
}
fun deductCoin(){
coin--
}
}
Now, If you will create 100 object or instance of “Coin” class. Your every object will refer to only 1 memory location
You can find the tutorial app for this in both of the languages
Java: https://github.com/gulnazghanchi/SingletonJava
Kotlin: https://github.com/gulnazghanchi/SingletonKotlin
Bonus: If you haven’t tried making your android app in Kotlin. I would suggest today is the day to start making your apps in Kotlin language.
In the next article: I am gonna use Singleton while using “Retrofit Library” which we use to call REST APIs in our applications.
Happy Coding!