Singleton Design Pattern in Kotlin and Java — Made Easy and Simple
What is a Singleton?
A Singleton is an object that can only be instantiated once during the life of an application; also known as a “single” instance. This is useful when only one object instance is desired to handle accessing functionality of a class.
How to create a Singleton in Kotlin
Creating a Singleton is quick and easy. simply declare a class using the object
keyword.
How to create a Singleton in Java
You can create a Singleton in 3 easy steps!
1. Define a class with private static
member variable to hold the single instance.
2. Define a private constructor to restrict the creation of any other instance of the class.
3. Define a static function that initializes and returns the static member variable. Check if the member variable is null to initialize it.
You can simplify step 3 by using the final
keyword when declaring the private static
member variable.
That’s it, super simple! You can find the example repository here! Follow me for more coding made simple content!
Want to learn about other Creational design patterns? Here are some others: