Описание тега singleton

A design pattern that ensures that exactly one application-wide instance of a particular class exists. One of the Gang of Four's creational design patterns.

Singleton is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

public class SingletonDemo {
    private static volatile SingletonDemo instance = null;

    private SingletonDemo() {
    }

    public static SingletonDemo getInstance() {
        if (instance == null) {
            synchronized (SingletonDemo.class){
                if (instance == null) {
                    instance = new SingletonDemo ();
                }
            }
        }
        return instance;
    }
}

Implementations of Singleton may include additional features such as thread-safe initialization, or some form of initialization order.

Singleton is arguably the most well-known, the most used, the most abused, and the most disputed design pattern in existence, frequently leading to heated discussions between its proponents and opponents.

This is one of the Gang of Four's creational design-patterns, first published in Gamma et al.'s book "Design Patterns: Elements of Reusable Object-Oriented Software".

More information is available on Wikipedia.