Singleton Design Pattern

Josh - Jun 10 '21 - - Dev Community

Design patterns offer established solutions for common problems in software engineering. They represent the best practices that have evolved over time. This is the start of a series of posts that I will be creating over common and popular design patterns that developers should be familiar with. I’m going to start with creational patterns that involve the creation of objects. They help reduce complexity and decouple classes in a standardized manner.

For this post, I am going to talk about the Singleton design pattern.

The Singleton design pattern was the first pattern that I was taught in college. It’s purpose is to initialize only one instance of an object and provide a method for it to be retrieved. This is done by making the constructor private with a public method that returns the instance created. If you try to initialize another instance the compiler will throw an error. There are different ways of implementing this pattern and I will provide an example below pulled from tutorialspoint.com.

public class Singleton {

    private static Singleton singleton = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
        return singleton;
    }
}
Enter fullscreen mode Exit fullscreen mode

When would you use the Singleton design pattern?

  • Creation of objects that are computationally expensive
  • Creation of loggers used for debugging
  • Classes that are used to configure settings for an application
  • Classes that hold or access resources that are shared

The Singleton pattern does come with some detractors however that believe that it is an anti-pattern. Many believe that it is not used correctly and that novice programmers use it too often. Forums also state that creating a container that holds and accesses the single class object is a much better solutions in modern applications. Whether or not this design pattern is useful to new developers seems to be up to debate. Let me know what you think in the comments below!

Sources

  1. Baeldung. (2019, September 11). Introduction to Creational Design Patterns. Baeldung. https://www.baeldung.com/creational-design-patterns.

  2. Java - How to Use Singleton Class? Tutorialspoint. (n.d.). https://www.tutorialspoint.com/java/java_using_singleton.htm.

. . . . . . . . . . . . . . . . . . . . .