DEV Community

Cover image for Design Patterns: Singleton
Tamerlan Gudabayev
Tamerlan Gudabayev

Posted on • Updated on

Design Patterns: Singleton

This week on design patterns, we have the Singleton.

It's the last creational design pattern that we will cover.

Today you will learn:

  • Understand the core concepts of the Singleton pattern.
  • Understand why the Singleton pattern is considered an anti-pattern.
  • Recognize opportunities to use the Singleton pattern.
  • Understand the pros and cons of the Singleton pattern.

Definition

Alt Text

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance. — Wikipedia

In a nutshell, the Singleton Pattern:

  • Ensures that a class only has a single instance

    But why would we want to have only a single instance of a class?

    There might be many different use-cases, but the most common would be the ability to access some shared resource - a database or file.

    In essence, if you created an object, and then wanted to create a new one. You would not get a fresh object instead, get the old one you created.

    Keep in mind that this behaviour is almost impossible to implement in the regular constructor since it must always return a new object.

  • Provide global access to that instance

    Basically, we would want our instance to be accessible anywhere in the code base, that's why we make that instance globally accessible. This also protects our instance from being overwritten by other objects.

    However, this may be very unsafe, due to the instance being global.

    This is one of the reasons why critics consider the Singleton Pattern an Antipattern.

What is an Antipattern?

Alt Text

At the beginning of the series we have defined the design pattern, they are basically a common solution to a recurring problem.

On the other hand, an Antipattern is a common solution to a recurring problem THAT has negative consequences in the long run.

Antipatterns aren't specifically software related, they can be managerial problems or even architectural problems.

In our case, the Singleton pattern is considered to be an Antipattern due to the fact:

  • Tightly couples your code to a Singleton.
  • Introduced lot's of complexity if your application is multi-threaded.
  • They are hard to test because they are global.

BUT in the right environment and implementation, Singletons can be a good option.

Implementation

There are different ways to implement a Singleton, but they all these two steps:

  • Make your constructor private to prevent other objects from creating new instances of the Singleton class.
  • Create a public static creation method to return a new or recurring instance. Under the hood, it checks whether the class already has an instance or not, and acts appropriately.

Here's a naive example using JavaScript:

class Singleton {

    private static instance; 

    private constructor() {]

    public function getInstance(){
        if (!Singleton.instance) {
            Singleton.instance = new Singleton();
        }

        return Singleton.instance;
    }

}
Enter fullscreen mode Exit fullscreen mode

When to use this pattern?

Use the Singleton pattern when you only want a single instance of a class, this may be a database or some logger object that would be shared across your program.

The Singleton Pattern disables all other means of creating another instance of a class, which guarantees that the instance is either a newly created one or an existing one.

Pros

  • You can be sure that a class only has a single instance.
  • You have global access to that single instance.
  • The Singleton object is only initialized when it's requested the first time.

Cons

  • Violates the Single Responsibility Principle. The pattern solves two problems at the time.
  • Your code gets coupled to the Singleton.
  • Get's very complex in multi-threaded applications.
  • It's hard to unit test because it's gonna be hard to mock the Singleton due to its constructor being private.

Conclusion

The Singleton pattern is a controversial one, some say it's good other's say it's bad.

It depends actually, in some rare use-cases it can be very useful, and now you have this pattern in your toolbox.

Today you learned:

  • Core concepts of the Singleton pattern
  • Its basic implementation
  • Its pros and cons

Further Readings

If you want to learn more about the design patterns, I would recommend Diving into Design Patterns. It explains all 23 design patterns found in the GoF book, in a fun and engaging manner.

Another book that I recommend is Heads First Design Patterns: A Brain-Friendly Guide, which has fun and easy-to-read explanations.

Top comments (1)

Collapse
 
ajunquit profile image
Alejandro Junqui

Thanks for share with us.