Computer Science

Singleton Pattern

The Singleton Pattern is a design pattern that restricts the instantiation of a class to one object. It ensures that only one instance of the class is created and provides a global point of access to that instance. This pattern is commonly used in situations where a single instance of a class is required to coordinate actions across a system.

Written by Perlego with AI-assistance

11 Key excerpts on "Singleton Pattern"

  • Book cover image for: TypeScript 4 Design Patterns and Best Practices
    Singleton pattern. We will start by learning what a Singleton is and what problems it can solve. Then, you will study both the classic implementation and some modern alternatives. Finally, we list some of the major disadvantages of Singletons.
    The term Singleton describes something that has only a single presence in the program. You use it when you want to get hold of a single object instead of many different ones for several reasons. For example, maybe you want to keep only one instance of a particular class simply because it is either expensive to create or it does not make sense to keep more than one for the lifetime of the program.
    Note
    When we mention a program, we refer to the current runtime environment, which in most cases consists of a single process that has access to all program memory. Due to the Operating System (OS ) and other considerations, when you spawn another process, it will create its own Singleton instances.
    Consider the following key observations to help you understand the Singleton Pattern:
    • Global access point : When you have a Singleton, you essentially have one and only one access point of its instance. That's why a lot of times you find that the Singleton is just another name for global instance .
    • The instance is cached somewhere : You cache the instance of the Singleton object somewhere so that you can retrieve it on demand. Typically, you store it within the class instance itself as a static variable, but it can be stored inside an Inversion of Control (IoC ) container as well.
    • The instance is created on demand : The instance is not created the moment it's declared. Instead, it is created lazily, in a First In First Out (FIFO
  • Book cover image for: Software Architecture for Busy Developers
    Usually, there are pros and cons for everything we do, but this does not apply to DI. It is a no-brainer that DI is strongly encouraged in every project. For this one, I authorize you to be the cargo cult developer. Let's now explore another well-known (anti-)pattern— namely, the Singleton Pattern.

    Exploring the singleton design pattern

    The Singleton Pattern, part of the creational category, is often subject to controversy because it is not always used appropriately. It is even considered an anti-pattern by many. However, this pattern is sometimes necessary for heavy objects. By heavy, I mean objects that take a long time to initialize or consume a lot of resources when being initialized.
    The purpose of the Singleton Pattern is to instantiate a given object only once per application domain. This means that the object will be created once and shared for the entire lifetime of the application, which is why it is important to use it wisely because it also comes with a whole bunch of drawbacks. The following diagram shows a single instance that is shared across consumers:
    Figure 5.11 – Singleton design pattern
    In the case of a web application, every separate HyperText Transfer Protocol (HTTP ) request hits the same instance of a given singleton. Let's now see the Singleton Pattern in action.

    Singleton Pattern in action

    The following code is the default startup method of a console application:
    Figure 5.12 – Singleton main method
    As you can see from the preceding code snippet, I use a parallel for loop to simulate a high concurrency. In the loop, I get an instance of  ThreadSafeSingletonExample and NotThreadSafeSingletonExample objects. Here is the implementation of NotThreadSafeSingletonExample :
    Figure 5.13 – Non-thread-safe singleton implementation
    As their names indicate, one implementation is thread-safe while the other is not. With this example, I want to illustrate one of the major drawbacks of singletons—namely, thread safety. Under a high load, you may end up with multiple instances of a singleton if you do not pay attention to concurrency, which leads to unexpected outcomes because the main purpose of a singleton is to have a single instance in all circumstances. Moreover, such beginner errors may not be visible directly and might show up later once an application is already in production. This is not that easy to troubleshoot, so you'd better flush such issues out soon enough.
  • Book cover image for: Java Professional Interview Guide
    eBook - ePub

    Java Professional Interview Guide

    Learn About Java Interview Questions and Practise Answering About Concurrency, JDBC, Exception Handling, Spring, and Hibernate

    java.lang.Runtime is based on the Singleton Pattern. The Singleton Pattern enables defining a class that has only one instance and provides a global point of access to that instance. It means, it is the responsibility of the class to offer a mechanism that should create a single instance, and all other classes can use that single object.

    How to implement the Singleton Pattern?

    • The two ways of creating a Singleton Pattern are as follows:
    • Early instantiation: In early instantiation, the instance will be created at load time. The following code represents how to implement the singleton design pattern for early instantiation:
      public class EarlySingleton
      {
      private static EarlySingleton earlySingleton = new
      EarlySingleton();
      private EarlySingleton () {}
      public static EarlySingleton getInstance ()
      {
      return earlySingleton;
      } }
    • Lazy instantiation: In lazy initialization, the instance is created only when required. The following code represents how to implement the singleton design pattern for lazy instantiation:
      public class LazySingleton
      {
      private static LazySingleton lazySingleton;
      private LazySingleton () {}
      public static LazySingleton getInstance ()
      {
      if (lazySingleton==null )
      lazySingleton = new LazySingleton();
      return lazySingleton;
      } }

    What are the limitations and disadvantages of the Singleton Pattern?

    Limitation of the singleton design pattern:
    The Singleton Pattern ensures the class has only one instance along with providing a global point of access to it. This single instance becomes the limitation because most of the classes in the application might need to create multiple instances.
  • Book cover image for: Java 8 to 21
    eBook - PDF

    Java 8 to 21

    Explore and work with the cutting-edge features of Java 21 (English Edition)

    The true value of patterns is linguistic. We can describe complex behaviors by simply bringing up the pattern. These behaviors are often language agnostic and help us OOP Patterns  35 build a mental model of a system without a detailed understanding of the specific mechanics involved. Singleton The Singleton is probably the most universally recognizable pattern. It is also commonly considered an anti-pattern. Despite that, it is widely used; we can see it in the Java API in classes such as Desktop or Runtime. Let us start by defining the simplest Singleton possible: 1. public class SimpleSingleton { 2. private static final SimpleSingleton INSTANCE = new SimpleSingleton(); 3. 4. private SimpleSingleton() {} 5. 6. public static SimpleSingleton getInstance() { 7. return INSTANCE; 8. } 9. 10. public void doSomething() { 11. // code 12. } 13. } A Singleton is a class for which we can have only one instance. This is roughly the equivalent of having a class where all the methods are static. Notice that the instance of the class is created statically in this case, and the constructor is private. That means the code that will try to create an instance of SimpleSingleton will fail. The only way to get the instance is through the getInstance() method. Why do we need this pattern if we can just use static methods? The main benefit of a singleton is in its ability to evolve as an API. Following is a more realistic example of a singleton. In this case, the instance of the class is specific to the platform we are running on. In this way, our class can provide different functionality when running on Windows or on a Mac. This would be seamless to the rest of the code: 36  Java 8 to 21 1. public abstract class PlatformSingleton { 2. private static final PlatformSingleton INSTANCE; 3. 4. static { 5. if(System.getProperty("os.name").toLowerCase(). contains("mac")) { 6. INSTANCE = new Mac(); 7. } else { 8.
  • Book cover image for: An Atypical ASP.NET Core 5 Design Patterns Guide
    eBook - ePub

    An Atypical ASP.NET Core 5 Design Patterns Guide

    A SOLID adventure into architectural principles, design patterns, .NET 5, and C#

    The Singleton design pattern allows creating and reusing a single instance of a class. We could use a static class to achieve almost the same goal, but not everything is doable using static classes. For example, implementing an interface or passing the instance as an argument cannot be done with a static class; you cannot pass static classes around, you can only use them directly.
    In my opinion, the Singleton Pattern in C# is an anti-pattern. Unless I cannot rely on Dependency Injection, I don't see how this pattern could serve a purpose. That said, it is a classic, so let's start by studying it, then move to a better alternative in the next chapter.
    Here are a few reasons why we are covering this pattern:
    • It translates into a singleton scope in the next chapter.
    • Without knowing about it, you cannot locate it, nor try to remove it – or avoid its usage.
    • It is a simple pattern to explore, and it leads to other patterns, such as the Ambient Context pattern.

    Goal

    The Singleton Pattern limits the number of instances of a class to one. Then, the idea is to reuse the same instance subsequently. A singleton encapsulates both the object logic itself and its creational logic. For example, the Singleton Pattern could lower the cost of instantiating an object with a large memory footprint since it's instantiated only once.
    Can you think of a SOLID principle that gets broken right there?

    Design

    This design pattern is straightforward and is limited to a single class. Let's start with a class diagram:
    Figure 6.6 – Singleton Pattern class diagram
    The Singleton class is composed of the following:
    • A private static field that holds its unique instance.
    • A public static Create() method that creates or returns the unique instance.
    • A private constructor, so external code cannot instantiate it without passing by the Create method.Note
      You can name the Create() method anything or even get rid of it, as we'll see in the next example. We could name it GetInstance() , or it could be a static property named Instance
  • Book cover image for: Beginning Java Programming
    eBook - ePub

    Beginning Java Programming

    The Object-Oriented Approach

    • Bart Baesens, Aimee Backiel, Seppe vanden Broucke(Authors)
    • 2015(Publication Date)
    • Wrox
      (Publisher)
    Here, the singleton, static utility class, service provider (this pattern is not mentioned in the Gang of Four book but is closely related to the Singleton Pattern), factory, and abstract factory patterns are covered. The builder and prototype creational patterns are not discussed, as both of them are less commonly applied in Java.
    Singleton Pattern and Static Utility Class
    Let’s start with one of the most controversial object-oriented patterns, the Singleton Pattern. (We’ll address the reasons behind its controversy later on.) The Gang of Four summarizes a design pattern as follows:
    Ensure a class has instance and provide a global point of access to that instance.
    This pattern is useful whenever exactly one object is needed to coordinate certain actions. In Java, an easy way to define a singleton class is as follows:
    public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton getInstance() { return INSTANCE; } // Other public methods follow here }
    You call the singleton ’s methods as follows:
    Singleton.getInstance().theSingletonMethod();
    Note the different aspects at play here. First of all, the static final field is immediately initialized to contain the single singleton object (which cannot be changed afterward due to being final). Second, direct instantiation of objects is prohibited by making the constructor private. Third, the single instance is accessed calling the public static getInstance() method.
    This way of defining a singleton class is called “eager initialization,” as the single instance gets created no matter whether it will be used during the execution of the program. The alternative, called “lazy initialization,” first sets the INSTANCE (nonfinal, then) field to null and initializes it the first time the getInstance()
  • Book cover image for: Hands-On Design Patterns with Delphi
    No longer available |Learn more

    Hands-On Design Patterns with Delphi

    Build applications using idiomatic, extensible, and concurrent design patterns in Delphi

    Singleton, Dependency Injection, Lazy Initialization, and Object Pool

    In Object-Oriented Programming (OOP ), everything starts with an object, and if we want to use one, we have to create it first. In most cases, that simply means calling TSomeClass.Create, but in a more complex scenario, a specialized design pattern that creates an object for us can be quite handy.
    In this chapter, we'll look into four patterns from the creational group. At the end of the chapter, you'll know the following:
    • A Singleton Pattern, which makes sure that a class has only one instance
    • A dependency injection pattern, which makes program architecture more flexible and suitable for test-driven development
    • A lazy initialization pattern, which makes sure that we don't spend time and resources creating objects that we don't really need
    • An object pool pattern, which speeds up the creation of objects that take a long time to create
    Passage contains an image

    Singleton

    The singleton pattern was part of the original Design Patterns collection. It makes sure that a class, which we call a singleton class, has only one instance. In other words, only one object of that class may ever be created during the program's life. Such a class must also provide global access to this instance.
    Let me give a real-life example to clarify this definition. You probably live in a country that allows one, and only one, president (or monarch, head of state, and so on.) to exist at the same time. So, that person is a singleton.
    You will notice that the pattern tells us nothing about how that one singleton instance should be destroyed. It also doesn't specify when the singleton instance should be created.
  • Book cover image for: An Atypical ASP.NET Core 6 Design Patterns Guide
    • Carl-Hugo Marcotte, Abdelhamid Zebdi(Authors)
    • 2022(Publication Date)
    • Packt Publishing
      (Publisher)
    public static MyAmbientContext Current { get; set; } ), and it could support more complex mechanics. As always, it is up to you and your specifications to build the right classes exposing the right behaviors.
    To conclude this interlude: try to avoid ambient contexts and use instantiable classes instead. We see how to replace a singleton with a single instance of a class using dependency injection in the next chapter. That gives us a more flexible alternative to the Singleton Pattern.

    Conclusion

    The Singleton Pattern allows the creation of a single instance of a class for the whole lifetime of the program. It leverages a private static field and a private constructor to achieve its goal, exposing the instantiation through a public static method or property. We can use a field initializer, the Create method itself, a static constructor, or any other valid C# options to encapsulate the initialization logic.
    Now let’s see how the Singleton Pattern can help us (not) follow the SOLID principles:
    • S : The singleton violates this principle because it has two clear responsibilities:
      1. It has the responsibility for which it has been created (not illustrated here), like any other class.
      2. It has the responsibility of creating and managing itself (lifetime management).
    • O : The Singleton Pattern also violates this principle. It enforces a single static instance, locked in place by itself, which limits extensibility. The class must be modified to be updated, impossible to extend without changing the code.
    • L : There is no inheritance directly involved, which is the only good point.
    • I : There is no interface involved, which is a violation of this principle.
    • D : The singleton class has a rock-solid hold on itself. It also suggests using its static property (or method) directly without using an abstraction, breaking the DIP with a sledgehammer.
    As you can see, the Singleton Pattern does violate all the SOLID principles but the LSP and should be used with caution. Having only a single instance of a class and always using that same instance is a legitimate concept. However, we see how to properly do this in the next chapter, leading me to the following advice: do not use the Singleton Pattern, and if you see it used somewhere, try refactoring it out. Another good idea is to avoid the use of static members as much as possible as they create global elements that can make your system less flexible and more brittle. There are occasions where static members are worth using, but try keeping their number as low as possible. Ask yourself if that static
  • Book cover image for: Kotlin for Enterprise Applications using Java EE
    No longer available |Learn more

    Kotlin for Enterprise Applications using Java EE

    Develop, test, and troubleshoot enterprise applications and microservices with Kotlin and Java EE

    A singleton is a class whose instance can be created only once. This exists until the application is up and running. A singleton class provides a single access point that has to be used to get the instance of the class. It restricts the number of instances of a class to one and controls the creation of instances of the class.
    A singleton class in an application is used when managing things such as memory, connection pools, threads, logging, and the registry. This ensures the consistency, reliability, and correctness of the data that classes handle in the application.
    Passage contains an image

    Writing a singleton class in Java

    Let's understand how to write a singleton class in Java. We then compare it with the singleton class in Kotlin. Let's consider the following class: public class Singleton { public String getDetails() { System.out.println ("running the method"); return "this is a singleton class"; }} If we want to instantiate this class, we do it as follows: new Singleton (); Calling a constructor like this gives an instance of this class. If we repeatedly call this constructor, we get multiple instances of the same class and it is therefore not a Singleton Pattern. Now we want only one instance of this class to be created and reused. To create a singleton class, we need to do the following:
    • Make the constructor private and initialize it within the class.
    • Provide a way to access the instance that is initialized.
    Marking the constructor of the class private will ensure that the constructor is invoked only from that class, thus controlling the instantiation the class. This constructor can't be invoked outside of the class; only the code within the singleton class can invoke the constructor, as follows:
    private Singleton() {} If there is no zero-argument constructor and if the constructor takes some argument for initializing the member instance, we can mark that constructor as private: private Singleton(String name) { this.name = name;}
    Now we need to use this private constructor to initialize the instance and provide a way to access it. This way, the instance is initialized within the class only and made available for usage in the application globally . Let's write a function that calls the private constructor of the singleton class:
  • Book cover image for: Architectural Patterns
    • Pethuru Raj Chelliah, Harihara Subramanian, Anupama Murali, Dr. Kayarvizhy N(Authors)
    • 2017(Publication Date)
    • Packt Publishing
      (Publisher)
    rather than creating a new object . Choose this pattern when a system should be independent of its products creation, compose, and representation:
    We can create a copy of PublicProfile (limited information) or FullProfile at runtime. Those two classes share a few combination of states, so it is good that we design as a prototype.
    Let's take a look at its benefits:
    • Adding and removing products at runtime
    • Specifying new objects by varying values and structures
    • Reduced subclasses
    • Dynamic class configuration to an application
    The impact is, each subclass must implement clone operation, and it is not possible to clone circular reference classes. Passage contains an image

    Singleton

    This pattern suggests that you create one and only one instance and provide a global point of access to the created object: The DB connection in the preceding diagram is intended to be a singleton and provides a getter for its only object. Here are its benefits:
    • Controlled access to a sole instance
    • Reduced namespace
    • Flexibility to refinement of operations and representations
    • More flexible than class operations
    Impacts are as follows:
    • Carry states for the whole lifetime of the application, creating additional overhead for unit tests
    • Some level of violation of single responsibility principle
    • By using singleton as a global instance, it hides the dependencies of the application; rather, it should get exposed through interfaces
    Passage contains an image

    Structural design patterns

    The structural patterns provide guidelines to compose classes and objects to form a larger structure in accordance with the OO design principles. The structural class pattern uses inheritance to compose interfaces or implementations, and structural object patterns advocate ways to compose objects and realize the new functionality.
  • Book cover image for: Pattern-Oriented Software Architecture, On Patterns and Pattern Languages
    • Frank Buschmann, Kevlin Henney, Douglas C. Schmidt(Authors)
    • 2007(Publication Date)
    • Wiley
      (Publisher)
    412 Referenced Patterns constraint. In addition, it is hard to evolve S INGLETON -based designs, since singletons are often tightly coupled to a particular context, just like global variables. Sink The S INK pattern [Ray04] characterizes non-interactive programs that only take data on the standard input and emit no output. Smart Pointer The S MART P OINTER pattern for C++ [Mey96] [Hen05a] helps to control access to objects accessed through a level of indirection. A class defines conventional pointer operations, such as operator* and operator-> , so that access to the target object is provided but is also managed. Software Above the Level of a Single Device The S OFTWARE A BOVE THE L EVEL OF A S INGLE D EVICE pattern [ORei05] [MuOr+07] increases the value of Web applications by ensuring that they are designed with integration and multiple targets in mind, rather than from a PC-centric perspective. Some Rights Reserved The S OME R IGHTS R ESERVED pattern [ORei05] encourages the use of existing standards and nonrestrictive licenses for Web sites to in-crease experimentation, collective adoption, aggregation, and mixing. Source The S OURCE pattern [Ray04] characterizes non-interactive programs that only emit data on the standard output stream and take no input. Stable Intermediate Forms The S TABLE I NTERMEDIATE F ORMS pattern [Hen04a] reduces the risk in-volved in a process of change. Any change from one state of affairs to another that cannot be characterized as atomic inevitably involves a number of steps, any one of which could fail for one reason or another, leaving the change incomplete and the circumstances uncertain. Risk can be reduced by ensuring that each intermediate step in the pro-cess of change expresses a coherent state, one that in some meaning-ful way represents a whole rather than a partial state of affairs.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.