Objects and Singletons
The Singleton Design Pattern, discussed in Design Patterns: Elements of Reusable Object-Oriented Software [GHJV95], is one of the easiest to understand and yet one of the most difficult to implement. It turns out that controlling the number of instances of a class isn’t a trivial task—you need to prevent reflective access to constructors, ensure thread safety, and, at the same time, not introduce any overhead to check if an instance exists. By providing support for singletons directly, Kotlin removes the burden of implementing the pattern and the risks of getting it wrong. When you need, you can directly create an object without being forced to first define a class. For simple situations you can use objects, and for more ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access