Learning Singleton Pattern

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

The Singleton Design Pattern

The singleton pattern is a creational pattern that produces a single instance of an object throughout an app. Singletons achieve this by restricting how objects are created and making them globally accessible. This is useful in circumstances where multiple instances of an object aren’t desirable. For instance, it may not be best to create a database connection each time you need to access the database. Instead, you may keep a single instance of the first connection and make it available to any class that needs it. The same is true for loggers, caches, thread pools, and some other object types.

Learning When to Use Singletons

Singletons are helpful when it’s expensive to create an object. If you can safely use one instance of a resource-intensive object throughout your app, you probably should make it a singleton to avoid creating it multiple times. This also prevents code duplication since there’s only one place to access singletons. Having a single instance of an object means you reduce the amount of memory your app uses. Access to singletons is better controlled since you only need to look in one place or class to find and manage its creation. Making objects available globally provides easy access to objects that require it.

Disadvantages of the Singleton Pattern

This pattern could lead to a memory leak if not properly handled or disposed of after use. Providing singletons globally can make it difficult to track how they’re used in the app. Singletons can also be difficult to test. Extra steps are necessary to make singletons thread-safe, increasing the app’s overall complexity. Singletons promote tight coupling and hidden dependencies, which go against the SOLID principles.

See forum comments
Download course materials from Github
Previous: Exploring Design Patterns Next: Implementing Singleton Pattern