请输入您要查询的百科知识:

 

词条 Singleton pattern
释义

  1. Overview

  2. Common uses

  3. Implementation

      C# implementation    Lazy initialization  

  4. Notes

  5. References

  6. External links

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system. The term comes from the mathematical concept of a singleton.

Critics consider the singleton to be an anti-pattern in that it is frequently used in scenarios where it is not beneficial, 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]

Overview

The singleton[4]

design pattern is one of the twenty-three well-known "Gang of Four" design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.

The singleton design pattern solves problems like:[5]

  • How can it be ensured that a class has only one instance?
  • How can the sole instance of a class be accessed easily?
  • How can a class control its instantiation?
  • How can the number of instances of a class be restricted?

The singleton design pattern describes how to solve such problems:

  • Hide the constructor of the class.
  • Define a public static operation (getInstance()) that returns the sole instance of the class.

The key idea in this pattern is to make the class itself responsible for controlling its instantiation (that it is instantiated only once).

The hidden constructor (declared private) ensures that the class can never be instantiated from outside the class.

The public static operation can be accessed easily by using the class name and operation name (Singleton.getInstance()).

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 do not pollute the global namespace (or, in languages with nested namespaces, their containing namespace) with unnecessary variables.[4]
    • They permit lazy allocation and initialization, whereas global variables in many languages will always consume resources.

Implementation

An implementation of the singleton pattern must:

  • ensure that only one instance of the singleton class ever exists; and
  • provide global access to that instance.

Typically, this is done by:

  • declaring all constructors of the class to be private; and
  • 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 the static method is first called. The following is a sample implementation written in Java.

public final class Singleton {

    public static Singleton getInstance() {        return INSTANCE;    }

}

C# implementation

public sealed class Singleton {

    public static Singleton Instance {        get {            return INSTANCE;        }    }

}

In C# you can also use static classes to create singletons, where the class itself is the singleton.

public static class Singleton {

    public static MyOtherClass Instance {        get {            return INSTANCE;        }    }

}

Lazy initialization

A singleton implementation may use lazy initialization, where the instance is created when the static method is first invoked. If the static method might be called from multiple threads simultaneously, measures may need to be taken to prevent race conditions that could result in the creation of multiple instances of the class. The following is a thread-safe sample implementation, using lazy initialization with double-checked locking, written in Java.{{efn|In Java, to avoid the synchronization overhead while keeping lazy initialization with thread safety, the preferred approach is to use the initialization-on-demand holder idiom.{{cn|date=March 2017}}}}

public final class Singleton {

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

}

Notes

{{notelist}}

References

1. ^Scott Densmore. [https://blogs.msdn.microsoft.com/scottdensmore/2004/05/25/why-singletons-are-evil/ Why singletons are evil], May 2004
2. ^Steve Yegge. Singletons considered stupid, September 2004
3. ^Clean Code Talks - Global State and Singletons
4. ^{{cite book|author=Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides|title=Design Patterns: Elements of Reusable Object-Oriented Software|year=1994|publisher=Addison Wesley|isbn=0-201-63361-2|pages=127ff}}
5. ^{{cite web|title=The Singleton design pattern - Problem, Solution, and Applicability|url=http://w3sdesign.com/?gr=c05&ugr=proble|website=w3sDesign.com|accessdate=2017-08-16}}

External links

{{external links|date=November 2016}}{{wikibooks|Computer Science/Design Patterns|Singleton|Singleton implementations in various languages}}{{commons category}}
  • Complete article "Singleton Design Pattern techniques"
  • Four different ways to implement singleton in Java "[https://web.archive.org/web/20131002003845/http://www.javaexperience.com/design-patterns-singleton-design-pattern/ Ways to implement singleton in Java]"
  • Book extract: Implementing the Singleton Pattern in C# by Jon Skeet
  • Singleton at Microsoft patterns & practices Developer Center
  • IBM article "Double-checked locking and the Singleton pattern" by Peter Haggar
  • IBM article "Use your singletons wisely" by J. B. Rainsberger
  • Javaworld article "Simply Singleton" by David Geary
  • Google article "Why Singletons Are Controversial"
  • Google Singleton Detector (analyzes Java bytecode to detect singletons)
{{Design Patterns Patterns}}{{DEFAULTSORT:Singleton Pattern}}

3 : Software design patterns|Anti-patterns|Articles with example Java code

随便看

 

开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。

 

Copyright © 2023 OENC.NET All Rights Reserved
京ICP备2021023879号 更新时间:2024/11/13 21:39:05