Design Patterns In Kotlin: Singleton
The easiest pattern to be implemented in Kotlin (only one line needed) is also very controversial. Although many people claim that the singleton pattern is actually an anti-pattern and frequently misused, in this story we are going to see how we can implement it in Kotlin and that it can be very useful when used appropriatelly.
What is a Singleton?
Singleton specifies that only an instance of a given class can exist and it will be used by the whole application. Thus, we have a single and global point of access to this object.
When you should use the Singleton Pattern
It should be used when you need to control concurrent access to shared resources or when a class is frequently used by many distinct parts of your system and this class does not manage any state of your application.
An example usually given is the implementation of Loggers. They are normally used by almost every class of a system and they do not return any information that affects the behaviour of the application.
The most hated pattern
When you search through the internet, you will see there is a consensus among developers that there is only a handful of cases where the singleton pattern should be used.
Not for nothing is it so unliked, whenever a class is specified as a Singleton it becomes less testable, less reusable and less configurable.
However, design patterns are a tool to help you understand the abstract concepts and a set of perspectives to approach a problem. Therefore, if an approach has proven to be effective and practical, you should be doing fine.
Implementation in Kotlin
Last, but not least, implemeting a singleton in Kotlin could not be easier than writing just a single line of code:
object Counter
And this is it, when Kotlin compiles it, you will have the implementation of a singleton.
In comparison to Java, you would need to do something like:
public class Counter {
// Eagerly Loading of singleton instance
private static Counter instance = new Counter(); private Counter(){
// private to prevent anyone else from instantiating
}
public static Counter getInstance(){
return instance;
}
}
And by adding a few lines of code, in Kotlin you would have:
object Counter {
private var counter: Int = 0
fun getCounter(): Int{
return counter
}
fun addCounter(){
counter += 10
}
fun deductCounter(){
counter--
}
}
Pretty easy, right? But should you be using it anyway?
Contribute
Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio
Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw
Follow Me on Social Media
Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.