ArticleslgStudy

computer science

Singleton pattern

Singleton pattern is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Singleton pattern rather than just read about it. In short: In object-oriented programming, the singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance. It is one of the well-known "Gang of Four" design patterns, which describe how to solve recurring problems in object-oriented software.

Singleton pattern — main illustration
Singleton pattern — illustration

Key takeaways

  • Singleton pattern belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Singleton pattern to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Singleton pattern from memory before moving on to harder problems.

Reference excerpt

In object-oriented programming, the singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance. It is one of the well-known "Gang of Four" design patterns, which describe how to solve recurring problems in object-oriented software. The pattern is useful when exactly one object is needed to coordinate actions across a system. More specifically, the singleton pattern allows classes to:

Ensure they only have one instance Provide easy access to that instance Control their instantiation (for example, hiding the constructors of a class) The term comes from the mathematical concept of a singleton.

Common uses Singletons are often preferred to global variables because they do not pollute the global namespace (or their containing namespace). Additionally, they permit lazy allocation and initialization, whereas global variables in many languages will always consume resources. The singleton pattern can also be used as a basis for other design patterns, such as the abstract factory, factory method, builder and prototype patterns. Facade objects are also often singletons because only one facade object is required. Logging is a common real-world use case for singletons, because all objects that wish to log messages require a uniform point of access and conceptually write to a single source. In Scala, the object keyword essentially defines a singleton object; the compiler creates exactly one instance of this structure, initializes it lazily the first time it is referenced, and makes it globally accessible. Defining a class and object of the same name creates a "companion object", which are Scala's equivalent of Java's static methods (which Scala does not have). In a dependency injection framework, a singleton is a service lifetime policy where the container creates only one instance of the class and shares that exact instance across the entire application; dependency injection singletons therefore are regular service classes rather than classes with private constructors and a static instance method. In Java Card, singleton exception instances are used because allocation of objects is expensive on smart cards; the exception instance is reused by a static void throwIt(short reason); method in each exception class.

Implementations Implementations of the singleton pattern ensure that only one instance of the singleton class ever exists and typically provide global access to that instance. Typically, this is accomplished by:

Declaring all constructors of the class to be private, which prevents it from being instantiated by other objects Providing a static method that returns a reference to the instance The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before when the static method is first called. Singletons are typically final, to enforce that only one instance exists by blocking inheritance; however, it may be intentionally not final in cases such as the multiton pattern.

Eagerly-instantiated The traditional, eagerly-instantiated implementation, in Java, is as follows:

In C++, the implementation is more intricate; the Java implementation is implicitly thread-safe, but the eager singleton in C++ requires double-checked locking with lock/mutex to guarantee thread safety. Additionally, special member functions must be made either private or deleted to ensure the invariant of only one instance existing is upheld.

Meyers singleton This is an implementation of the Meyers singleton, so named after Scott Meyers, author of More Effective C++, due to his recommendation of this implementation. This implementation is lazily instantiated, only constructing the instance the first time the execution reaches the definition line inside instance(), never allocating/constructing the object if instance() is never called. This initialization is guaranteed (since C++11) to be thread-safe without needing manual locks, through function-local static initialization. The Meyers singleton does not include a reset() method (unlike the earlier traditional implementation; however, one can be implemented if the singleton is held using a unique pointer), and destruction occurs at program exit (like all static variables). The program output is the same as above.

While the Meyers singleton is mostly unique to C++ due to C++'s function-local static variables with lazy thread-safe initialization, it can still be emulated in other languages. For example, in Java, one can use the initialization-on-demand holder idiom:

Enum singletons In Java, because enums are full classes (rather than just integral constants), an enum can be used to implement a singleton; any enum E in Java is implicitly final and inherits from java.lang.Enum<E>.

Lazy initialization A singleton implementation may use lazy initialization in which the instance is created when the static method is first invoked. In multithreaded programs, this can cause race conditions that result in the creation of multiple instances. The following Java 5+ example is a thread-safe implementation, using lazy initialization with double-checked locking.

In a manner similar to the Meyers singleton, one can use System.Lazy<T> in C# to use lazy initialization:

Criticism Some consider the singleton to be an anti-pattern that introduces global state into an application, often unnecessarily. This introduces a potential dependency on the singleton by other objects, requiring analysis of implementation details to determine whether a dependency actually exists. This increased coupling can introduce difficulties with unit testing. In turn, this places restrictions on any abstraction that uses the singleton, such as preventing concurrent use of multiple instances. Singletons also violate the single-responsibility principle because they are responsible for enforcing their own uniqueness along with performing their normal functions.

Avoidance through dependency injection Dependency injection can be used to avoid the singleton pattern. The singleton pattern enforces a structural restriction of only one instance of a class, but dependency injection focuses on how dependencies are passed around, avoiding the necessity of objects to look up their own global state. For example, in the following example, the OrderService is tightly coupled to DatabaseConnection; the database cannot be swapped and a different instance cannot be used.

… excerpt ends here. Continue reading the full article.

Illustrations

Singleton pattern: A class diagram exemplifying the singleton pattern.
A class diagram exemplifying the singleton pattern.

Worked examples

Example 1 — a first encounter with Singleton pattern

Start with the simplest possible case. Write down what Singleton pattern claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Singleton pattern before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Singleton pattern ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Singleton pattern

In research
Singleton pattern appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Singleton pattern in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Singleton pattern is common in secondary-school and first-year university syllabi. It links to neighbouring topics Anti-patterns, Software design patterns, so understanding it makes those chapters shorter.
In everyday life
Look for Singleton pattern outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Singleton pattern” →

How to study Singleton pattern in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Singleton pattern means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Singleton pattern out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Singleton pattern in simple terms?

In object-oriented programming, the singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance. It is one of the well-known "Gang of Four" design patterns, which describe how to solve recurring problems in object-oriented software.

Why does Singleton pattern matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Singleton pattern?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Singleton pattern.

Tags

  • Anti-patterns
  • Software design patterns

Keep exploring