Singleton pattern

Singleton pattern

In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting 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.

There are criticism to the use of the singleton pattern, as some consider it an anti-pattern, judging that it is overused, introduces unnecessary restrictions in situations where a sole instance of a class is not actually required, and introduces global state into an application.[1][2][3][4][5][6]

In C++ it also serves to isolate from the unpredictability of the order of dynamic initialization, returning control to the programmer.

Contents

Common uses

  • The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation.
  • Facade Objects are often Singletons because only one Facade object is required.
  • State objects are often Singletons.
  • Singletons are often preferred to global variables because:
    • They don't pollute the global name space (or, in languages with namespaces, their containing namespace) with unnecessary variables.[7]
    • They permit lazy allocation and initialization, whereas global variables in many languages will always consume resources.

Structure

Singleton UML class diagram.svg

Implementation

Implementation of a singleton pattern must satisfy the single instance and global access principles. It requires a mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among class objects. The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made private. Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, it really has to be a singleton.

The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.

The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is being instantiated.

Example

The Java programming language solutions provided here are all thread-safe but differ in supported language versions and lazy-loading. Since Java 5.0, the easiest way to create a Singleton is the enum type approach, given at the end of this section.

Lazy initialization

public class Singleton {
        private static Singleton _instance;
 
        private Singleton() {  }
 
        public static synchronized Singleton getInstance() {
                if (null == _instance) {
                        _instance = new Singleton();
                }
                return _instance;
        }
}

Traditional simple way

This solution is thread-safe without requiring special language constructs, but it may lack the laziness of the one above. The INSTANCE is created as soon as the Singleton class is initialized. That might even be long before getInstance() is called. It might be (for example) when some static method of the class is used. If laziness is not needed or the instance needs to be created early in the application's execution, or your class has no other static members or methods that could prompt early initialization (and thus creation of the instance), this (slightly) simpler solution can be used:

public class Singleton {
        private static final Singleton instance = new Singleton();
 
        // Private constructor prevents instantiation from other classes
        private Singleton() { }
 
        public static Singleton getInstance() {
                return instance;
        }
}

The solution of Bill Pugh

University of Maryland Computer Science researcher Bill Pugh has written about the code issues underlying the Singleton pattern when implemented in Java.[8] Pugh's efforts on the "Double-checked locking" idiom led to changes in the Java memory model in Java 5 and to what is generally regarded as the standard method to implement Singletons in Java. The technique known as the initialization on demand holder idiom, is as lazy as possible, and works in all known versions of Java. It takes advantage of language guarantees about class initialization, and will therefore work correctly in all Java-compliant compilers and virtual machines.

The nested class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized).

public class Singleton {
        // Private constructor prevents instantiation from other classes
        private Singleton() { }
 
        /**
        * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
        * or the first access to SingletonHolder.INSTANCE, not before.
        */
        private static class SingletonHolder { 
                public static final Singleton instance = new Singleton();
        }
 
        public static Singleton getInstance() {
                return SingletonHolder.instance;
        }
}

Alternatively, the inner class Singletonholder can be also substituted by implementing a Property which provides also access to the static final/readonly class members. Just like the lazy object in C#, whenever the Singleton.Instance Property is called, this singleton is instantiated for the very first time.

The Enum way

In the second edition of his book "Effective Java" Joshua Bloch claims that "a single-element enum type is the best way to implement a singleton"[9] for any Java that supports enums. The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.

public enum Singleton {
        INSTANCE;
}

This approach does provide a mechanism for global access when preventing from instantiating a class instance at all. Enum can be replaced with a construct, a static class field. Nonetheless, it doesn't provide a way when willing to instantiate an object in whatsoever manner when needed, for instance, lazy initialization. In other words, it doesn't offer a trigger manner like Singleton instance or Lazy Value.

Prototype-based singleton

In a prototype-based programming language, where objects but not classes are used, a "singleton" simply refers to an object without copies or that is not used as the prototype for any other object. Example in Io:

Foo := Object clone
Foo clone := Foo

Example of use with the factory method pattern

The singleton pattern is often used in conjunction with the factory method pattern to create a system-wide resource whose specific type is not known to the code that uses it. An example of using these two patterns together is the Java Abstract Window Toolkit (AWT).

java.awt.Toolkit is an abstract class that binds the various AWT components to particular native toolkit implementations. The Toolkit class has a Toolkit.getDefaultToolkit() factory method that returns the platform-specific subclass of Toolkit. The Toolkit object is a singleton because the AWT needs only a single object to perform the binding and the object is relatively expensive to create. The toolkit methods must be implemented in an object and not as static methods of a class because the specific implementation is not known by the platform-independent components. The name of the specific Toolkit subclass used is specified by the "awt.toolkit" environment property accessed through System.getProperties().

The binding performed by the toolkit allows, for example, the backing implementation of a java.awt.Window to bind to the platform-specific java.awt.peer.WindowPeer implementation. Neither the Window class nor the application using the window needs to be aware of which platform-specific subclass of the peer is used.

Drawbacks

This pattern makes unit testing far more difficult,[6] as it introduces global state into an application.

It should also be noted that this pattern reduces the potential for parallelism within a program, because access to the singleton in a multi-threaded context must be serialised, e.g., by locking.

Advocates of dependency injection would regard this as an anti-pattern, mainly due to its use of private and static methods.

Some have suggested ways to break down the singleton pattern using methods such as reflection in languages such as Java[10][11] or PHP.[12]

References

  1. ^ Alex Miller. Patterns I hate #1: Singleton, July 2007
  2. ^ Scott Densmore. Why singletons are evil, May 2004
  3. ^ Steve Yegge. Singletons considered stupid, September 2004
  4. ^ J.B. Rainsberger, IBM. Use your singletons wisely, July 2001
  5. ^ Chris Reath. Singleton I love you, but you're bringing me down, October 2008
  6. ^ a b http://googletesting.blogspot.com/2008/11/clean-code-talks-global-state-and.html
  7. ^ Gamma, E, Helm, R, Johnson, R, Vlissides, J: "Design Patterns", page 128. Addison-Wesley, 1995
  8. ^ Pugh, Bill (November 16, 2008). "The Java Memory Model". http://www.cs.umd.edu/~pugh/java/memoryModel/. Retrieved April 27, 2009. 
  9. ^ Joshua Bloch: Effective Java 2nd edition, ISBN 978-0-321-35668-0, 2008, p. 18
  10. ^ Breaking the Singleton, September 21, 2009
  11. ^ Testing a Singleton, March 7, 2011
  12. ^ Singleton and Multiton with a different approach, July 21, 2010

External links



Wikimedia Foundation. 2010.

Игры ⚽ Поможем написать курсовую

Look at other dictionaries:

  • Singleton Pattern — Das Singleton (auch Einzelstück genannt) ist ein in der Softwareentwicklung eingesetztes Entwurfsmuster und gehört zur Kategorie der Erzeugungsmuster (engl. Creational Patterns). Es verhindert, dass von einer Klasse mehr als ein Objekt erzeugt… …   Deutsch Wikipedia

  • Singleton — may refer to *Singleton (mathematics), a set with exactly one element in mathematics *Singleton pattern, a design pattern used in software engineering *Singleton bound, used in coding theory *Singleton field, used in conformal field… …   Wikipedia

  • Singleton (Entwurfsmuster) — Das Singleton (auch Einzelstück genannt) ist ein in der Softwareentwicklung eingesetztes Entwurfsmuster und gehört zur Kategorie der Erzeugungsmuster (engl. Creational Patterns). Es verhindert, dass von einer Klasse mehr als ein Objekt erzeugt… …   Deutsch Wikipedia

  • Singleton variable — In computer programming a singleton variable is a variable that is referred to only once after it has been declared.Examples of where a variable might only be referenced once is as a dummy argument in a function call, or when its address is… …   Wikipedia

  • Singleton (Motif de conception) — Singleton (patron de conception) En génie logiciel, le singleton est un patron de conception (design pattern) dont l objet est de restreindre l instanciation d une classe à un seul objet (ou bien à quelques objets seulement). Il est utilisé… …   Wikipédia en Français

  • Singleton (motif de conception) — Singleton (patron de conception) En génie logiciel, le singleton est un patron de conception (design pattern) dont l objet est de restreindre l instanciation d une classe à un seul objet (ou bien à quelques objets seulement). Il est utilisé… …   Wikipédia en Français

  • Singleton — steht für: Singleton (Entwurfsmuster), ein Entwurfsmuster (Pattern) in der Softwareentwicklung Singleton (Bridge), eine nur einmal besetzte Farbe beim Kartenspiel Bridge Singleton (Texas), eine Stadt in Texas Singleton (West Sussex), ein Dorf in… …   Deutsch Wikipedia

  • Pattern theory — Pattern theory, formulated by Ulf Grenander, is a mathematical formalism to describe knowledge of the world as patterns. It differs from other approaches to artificial intelligence in that it does not begin by prescribing algorithms and machinery …   Wikipedia

  • Singleton (patron de conception) —  Pour l’article homonyme, voir Singleton.  En génie logiciel, le singleton est un patron de conception (design pattern) dont l objet est de restreindre l instanciation d une classe à un seul objet (ou bien à quelques objets seulement).… …   Wikipédia en Français

  • singleton — noun 1》 a single person or thing of the kind under consideration.     ↘a child or animal born singly, rather than one of a multiple birth.     ↘(in card games, especially bridge) a card that is the only one of its suit in a hand. 2》 informal a… …   English new terms dictionary

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”