

It gives some good insights when to use this design pattern. When to use a singleton?Īn interesting discussion is in going in StackOverflow. It has some similarities to the Borg Pattern.

In our example, however, we will use a bit more sophisticated use case. You could fake the singleton pattern by using a dependency injection framework.Ī common use case of the pattern is, for example, a globally accessible configuration class. Especially the last point is the reason why many people see this pattern actually as an “anti-pattern”. The negative part is that is difficult to implement it “right” in multithreading programs and it makes testing / mocking much more difficult. The good point of this pattern is, that it allows easy access to the object and you don’t need to think about the lifetime of the object. This pattern ensures that a class has only one instance and provides a global point of access to it. Design Patterns, Singleton Pattern What is a singleton?īefore we start diving into the implementation details we will shortly discuss the singleton pattern and its usages. The Gang Of Four described this pattern with the following words.Įnsure a class only has one instance, and provide a global point of access to it. With examples, we will show you how to create Kotlin singletons with parameters and with constructors. Kotlin provides some interesting native features to create and control singleton objects. This pattern is one of the most used and understood patterns in nowadays software. In this tutorial, we will cover the singleton design pattern.
