List of singleton implementations

from Wikipedia, the free encyclopedia

This is a list of implementations of the singleton design pattern in various programming languages.

Implementation in ActionScript

From version 2

(without protection against direct instantiation)

class Singleton {
    private static var _instance:SingletonClass;

    private function Singleton() {

    }

    public static function get instance():Singleton {
        if(!_instance) _instance = new Singleton();
        return _instance;
    }

    public function doSomething():Void {

    }
}

/* @use:
Singleton.instance.doSomething();
*/

From version 3

In ActionScript 3, constructors cannot be declared private. One possible solution is to use a private class to ensure that the constructor can only be called from within the singleton class:

package {
   public class Singleton {

      private static var _instance:Singleton = null;

      public function Singleton(se:SingletonEnforcer) {
         if(se === null) {
            throw new Error('Singleton kann nicht direkt erstellt werden. Verwende Singleton.instance');
         }
      }

      public static function get instance():Singleton {
         if(_instance === null) {
            _instance = new Singleton(new SingletonEnforcer() );
         }
         return _instance;
      }

   }
}

internal class SingletonEnforcer {}

Implementation in C #

Generally without thread safety

  // Nur zur Veranschaulichung – bitte nicht verwenden!
  class Singleton
  {
    private Singleton() { }
    private static Singleton instance = null;

    public static Singleton Instance
    {
       get
       {
          if (instance == null)
          {
             instance = new Singleton();
          }
          return instance;
       }
    }

  }

Use:

Singleton a = Singleton.Instance;
Singleton b = Singleton.Instance;

Assert.AreEqual(a,b);

Thread safe

A thread-safe method taken from MSDN Magazine.

class Singleton
{
  private Singleton() {  /* ...hier optional Initialisierungscode... */ }
  public static readonly Singleton Instance = new Singleton();
}

Use:

Singleton a = Singleton.Instance;
Singleton b = Singleton.Instance;

Assert.AreEqual(a,b);

The singleton principle is achieved in C # by two measures:

  1. By declaring the constructor as private ( private Singleton(){}), it can no longer be called from outside the class - the creation of the object is therefore only possible from within the class.
  2. The static public field Instance stores and provides read-only access to the only object in the class.
Important
The CLR does not automatically call the constructor when the program starts. Only when a class is accessed for the first time are all static members of the class initialized - in this case the instantiation of one object. So if that class is never accessed, the constructor will never run - and the object will never be created. This effect also occurs when the class itself is declared as static .

If you want to be sure that the singleton object is created when the program starts, you have to build any access into the main program ( public static void Main() { }).

Thread-safe with double-checked locking

The double-checked lockout is an anti-pattern . However, this variant works thread-safe and is often used by inexperienced developers.

class Singleton
{
  private Singleton() { }
  private static volatile Singleton instance;

  public static Singleton Instance
  {
    get
    {
      // DoubleLock
      if (instance == null)
      {
        lock(_lock)
        {
          if (instance == null)
            instance = new Singleton();
        }
      }
      return instance;
    }
  }

  // Hilfsfeld für eine sichere Threadsynchronisierung
  private static object _lock = new object();
}

Use:

Singleton a = Singleton.Instance;
Singleton b = Singleton.Instance;

Assert.AreEqual(a,b);

Notes on the code:

  • The private aid object _lockis absolutely necessary here. The earlier common method lock(this){ … }has proven to be inadequate because calling it bad or malicious code Monitor.Exit(Singleton);can easily undermine thread safety.
  • Double-lock pattern: So that the braking synchronization via lock () is omitted after the object has been instantiated, the same if query is also used in front of the lock section.
  • The volatile keyword means that the instance can be processed by several threads at the same time.

If there are no specific objections to the fact that the singleton object can also be instantiated earlier, the code described above is simpler and faster and is therefore preferable in C #.

Thread safe with synchronization

A bypass of the double-lock anti -pattern is to use the MethodImplattribute to ensure a synchronized method call. This corresponds to the keyword synchronizedin Java.

class Singleton
{
  private Singleton() { }
  private static volatile Singleton instance;

  public static Singleton Instance
  {
    [MethodImpl(MethodImplOptions.Synchronized)]
    get
    {
      if (instance == null)
        instance = new Singleton();
      return instance;
    }
  }
}

Use:

Singleton a = Singleton.Instance;
Singleton b = Singleton.Instance;

Assert.AreEqual(a,b);

Generic

A simple generic variant

public class Singleton<T> where T : class, new()
{
  private Singleton() { }

  private class SingletonCreator
  {
    static SingletonCreator() { }
    internal static readonly T instance = new T();
  }

  public static T Instance
  {
    get
    {
      return SingletonCreator.instance;
    }
  }
}

With this variant, the delegate constructor handshake pattern can be used to ensure that the public parameter-free constructor can only be called by the generic singleton class:

public class SomeSingleton
{
    public SomeSingleton(Singleton<SomeSingleton> caller)
    {
        if (caller == null)
        {
            throw new Exception();
        }
    }
}

Alternatively, System.Reflectionor System.Diagnosticscan be used to obtain information about the calling object. To do this, the object to be called must be passed in the constructor and analyzed. In addition, the new()condition is not met, which is why the corresponding construct has to be removed.

Generic with static factory method

In this variant, a static factory method is used to generate the singleton instance.

public class Singleton<T> where T : class
{
  // Methode zur Erzeugung einer neuen Instanz, welche als Delegat übergeben wird
  public delegate T CreateInstanceDelegate(Singleton<T> caller);
  private static CreateInstanceDelegate CreateInstanceMethod { get; set; }

  // Konstruktor
  public Singleton(CreateInstanceDelegate createInstanceMethod)
  {
    if (CreateInstanceMethod == null) throw new ArgumentNullException();
    CreateInstanceMethod = createInstanceMethod;
  }

  // Lock-Objekt für Threadsicherheit
  static readonly object Padlock = new Object();

  // Singleton-Instanz
  private static T _instance = null;
  public T Instance
  {
    get
    {
      lock (Padlock)
      {
        if (_instance == null)
          _instance = CreateInstanceMethod(this);
        return _instance;
      }
    }
  }
}

Commitment:

public sealed class SomeSingleton
{
  public static SomeSingleton CreateInstance(Singleton<SomeSingleton> caller)
  {
    return (caller == null) ? null : new SomeSingleton();
  }
  private SomeSingleton() { }
}

Use:

SomeSingleton a = new Singleton<SomeSingleton>(SomeSingleton.CreateInstance).Instance;
SomeSingleton b = new Singleton<SomeSingleton>(SomeSingleton.CreateInstance).Instance;

Assert.AreEqual(a,b);

Generic, abstract

public abstract class Singleton<T> where T : Singleton<T>
{
  private static T _instance;
  protected static bool IsInitialised { get { return (_instance != null); } }

  protected static T Instance { get { (IsInitialised) ? SingletonCreator.Instance : null; } }

  protected Singleton() { }

  protected static void Init(T newInstance)
  {
    if (newInstance == null) throw new ArgumentNullException();
    _instance = newInstance;
  }

  // da C# keine abstrakten statischen Methoden erlaubt,
  // wird die Erzeugung der Singleton-Instanz an diese Klasse weitergeleitet
  private class SingletonCreator
  {
    static SingletonCreator() { }
    internal static readonly T Instance = _instance;
  }
}

Commitment:

public sealed class SomeSingleton : Singleton<SomeSingleton>
{
  public static SomeSingleton Instance
  {
    get
    {
      (IsInitialised) ? return UniqueInstance : Init(new SomeGenericSingleton());
    }
  }

  private SomeSingleton() { }
}

Use:

SomeSingleton a = SomeSingleton.Instance;
SomeSingleton b = SomeSingleton.Instance;

Assert.AreEqual(a,b);

Generic, Abstract, Lazy

This is a generic abstract class that creates a singleton instance lazy .

public abstract class Singleton<T> where T : class
{
  // Lazy Instanziierung
  private static readonly Lazy<T> _instance = new Lazy<T>( () => CreateSingletonInstance() );

  public static T Instance
  {
    get
    {
      return _instance.Value;
    }
  }

  private static T CreateSingletonInstance()
  {
    // Konstruktion des Singleton-Objekts
    return Activator.CreateInstance(typeof(T), true) as T;
  }
}

Commitment:

class SomeSingleton : Singleton<SomeSingleton>
{
  // öffentliche Felder und Methoden
  public string SomeString {get; set; }

  // Konstruktor muss private sein
  private SomeSingleton()
  {
  }
}

Use:

SomeSingleton a = SomeSingleton.Instance;
SomeSingleton b = SomeSingleton.Instance;

Assert.AreEqual(a,b);

Generic with a call to a private constructor via reflection

The following variant calls a private constructor via reflection:

public class Singleton<T> where T : class
{
    private Singleton() { }

    private class SingletonCreator
    {
        static SingletonCreator() { Instance = CreateInstance(); }

        private static T CreateInstance()
        {
            ConstructorInfo constructorInfo = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, Type.DefaultBinder, Type.EmptyTypes, null);

            if (constructorInfo != null)
                return constructorInfo.Invoke(null) as T;
            else
                return null; // oder: throw new InvalidOperationException("Should have a private parameterless constructor");
        }

        internal static readonly T Instance { get; private set; }
    }

    public static T Instance
    {
        get { return SingletonCreator.Instance; }
    }
}

Commitment:

public class SomeSingleton : Singleton<SomeSingleton>
{
    private SomeSingleton() { }
}

Use:

SomeSingleton a = SomeSingleton.Instance;
SomeSingleton b = SomeSingleton.Instance;

Assert.AreEqual(a,b);

Implementation in C ++

Caution: The following two implementations are incorrect as more than one instance can be created if multiple threads call getInstance () at the same time. They only serve as an example and should not be used in this form in large projects without locking.

First method: has the advantage that the object is automatically destroyed at the end of the program (and the destructor is called). But you have no control over exactly when that happens.

class Singleton
{
private:
    Singleton() = default; // von außen keine Instanzen erzeugbar. Implementieren Sie wenn die Klasse nicht trivial ist

    Singleton(const Singleton&) = delete;// deaktiviere Kopie Konstruktor
    Singleton& operator=(const Singleton&) = delete; // deaktiviere Kopie Zuweisungsoperator
  
    ~Singleton() = default;
public:
    static Singleton& instance();
};

Singleton& Singleton::instance()
{
    static Singleton instance;
    return instance;
}

Second method: The advantage of this is that you can create a specialized object when you create the object, so you have polymorphism . In addition, by adding a static Destroy () function, you have full control over when the singleton is destroyed again.

   class Singleton
   {
   private:
      static Singleton* instance;
      Singleton() {}
      Singleton(const Singleton&) {}
      ~Singleton() {}
   public:
      static Singleton& getInstance();
      static void destroy();
   };

   Singleton* Singleton::instance = 0;

   Singleton& Singleton::getInstance()
   {
      if ( !instance )
         instance = new Singleton();
      return *instance;
   }

   void Singleton::destroy()
   {
      delete instance;
      instance = 0;
   }

Third method: Provides a base class to easily identify a class as a singleton.

   template <class T_DERIVED>
   class CSingleton
   {
      public:
         static T_DERIVED& GetInstance()
         {
            static T_DERIVED oInstance ;
            return oInstance ;
         }

      protected:
         CSingleton(){}

      private:
         CSingleton( const CSingleton& ) ;
         CSingleton& operator=( const CSingleton& ) {return *this;}
   } ;

   // Verwendung
   class CMySingleton : public CSingleton< CMySingleton >
   {
      friend class CSingleton< CMySingleton >;

      private:
         CMySingleton(){}

      //...
   };

Implementation in Delphi

Implementation from Delphi 5

unit Singleton;

interface

uses
  Windows, Dialogs, Forms, sysutils;

type
  TSingleton = class
  protected
    constructor CreateInstance;
    class function AccessInstance(Request: Integer): TSingleton;
  public
    constructor Create;
    destructor Destroy; override;

    Procedure MyFoo();

    class function Instance: TSingleton;
    class procedure ReleaseInstance;
  end;

implementation

//******************************************************************************
constructor TSingleton.Create;
begin
  inherited Create;
  raise Exception.CreateFmt('Access class %s through Instance only',
          [ClassName]);
end;

//******************************************************************************
constructor TSingleton.CreateInstance;
begin
  // Meine internen Dinge erzeugen
  // ...
  inherited Create;
end;

//******************************************************************************
destructor TSingleton.Destroy;
begin
  // Meine internen Dinge freigeben
  // ...

  if AccessInstance(0) = Self then AccessInstance(2);
  inherited Destroy;
end;

//******************************************************************************
class function TSingleton.AccessInstance(Request: Integer): TSingleton;
{$WRITEABLECONST ON}
const
     FInstance: TSingleton = nil;
{$WRITEABLECONST OFF}
begin
  case Request of
    0 : ;
    1 : if not Assigned(FInstance) then FInstance := CreateInstance;
    2 : FInstance := nil;
  else
    raise Exception.CreateFmt('Illegal request %d in AccessInstance',
            [Request]);
  end;
  Result := FInstance;
end;

//******************************************************************************
class function TSingleton.Instance: TSingleton;
begin
  Result := AccessInstance(1);
end; // Instance

//******************************************************************************
class procedure TSingleton.ReleaseInstance;
begin
  AccessInstance(0).Free;
end;

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure TSingleton.MyFoo();
begin
  // Mach was
end;

end.

Call:

  TSingleton.Instance.MyFoo();

Implementation from Delphi 2007

unit Singleton;

interface

uses
  SysUtils, Windows, Messages, Classes, Controls, StdCtrls, Forms, Dialogs;

type

  TSingleton = class(TInterfacedObject)
  private
    class var
      FInstance: TSingleton;

  protected
    constructor CreateInstance;
  public
    constructor Create(const Dummy:Integer = 0);
    destructor Destroy; override;

    Procedure MyFoo();

    class function Instance: TSingleton;
    class procedure ReleaseInstance;
  end;

implementation

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
constructor TSingleton.Create(const Dummy:Integer = 0);
begin
  inherited Create;
  raise Exception.CreateFmt('Access class %s through Instance only',
      [ClassName]);
end;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
destructor TSingleton.Destroy;
begin
  // Meine internen Dinge freigeben
  // ...

  if FInstance = Self then FInstance := nil;
  inherited Destroy;
end;

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
constructor TSingleton.CreateInstance;
begin
  // Meine internen Dinge initialisieren
  // ...
end;

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class function TSingleton.Instance: TSingleton;
begin
  if FInstance = nil then
    FInstance := CreateInstance;

  Result := FInstance;
end;

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class procedure TSingleton.ReleaseInstance;
begin
  if FInstance <> nil then
    FreeAndNil(FInstance);
end;

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Procedure TSingleton.MyFoo();
begin
  // Mach was
end;

end.

Call:

  TSingleton.Instance.MyFoo();

Implementation in Java

Enum

According to Joshua Bloch, the best way to implement a singleton in Java is as follows:

  public enum Singleton {
      INSTANCE;
      public void doSomething(){
            //TODO
      }
  }

Use:

Singleton.INSTANCE.doSomething()

This type worked from Java version 5, because Enums were only introduced with this version .

General

The creation of the unique existing object is achieved as follows:

  • The Singleton class constructor is private. So it is not possible to create another object of this class from the outside.
  • As a replacement, a new access method is created that can return a reference to the single object.
  • The variable in which the object is saved is given the modifier "static" ( static). It is also synchronized to ensure concurrent execution security. In Java , the object is only created when it is needed.
public final class Singleton
{
    /**
     * privates Klassenattribut,
     * wird beim erstmaligen Gebrauch (nicht beim Laden) der Klasse erzeugt
     */
    private static Singleton instance;

    /** Konstruktor ist privat, Klasse darf nicht von außen instanziiert werden. */
    private Singleton() {}

    /**
     * Statische Methode „getInstance()“ liefert die einzige Instanz der Klasse zurück.
     * Ist synchronisiert und somit thread-sicher.
     */
    public synchronized static Singleton getInstance()
    {
        if (instance == null)
        {
            instance = new Singleton();
        }
        return instance;
    }
}

The disadvantage of this variant is that even after the instantiation, every read access is getInstance()synchronized via and thus several threads accessing at the same time block each other. Implementations that do without synchronization using "double-checked locking" in an existing instance are generally not thread-safe.

Lazy instantiation

In Java , this implementation is preferable to the lazy creation approach. The initialization does not take place due to the late initialization of the class until the class is Singletonreferenced. Since access is only via getInstance(), this is the latest possible time and thus corresponds to the lazy evaluation without the synchronization overhead.

  public final class Singleton {

      /** Privates Klassenattribut, einzige Instanz der Klasse wird erzeugt. */
      private static final Singleton INSTANCE = new Singleton();

      /** Konstruktor ist privat, darf nicht von außen aufgerufen werden. */
      private Singleton() {}

      /** Statische Methode „getInstance()“ liefert die einzige Instanz der Klasse zurück. */
      public static Singleton getInstance() {
          return INSTANCE;
      }
      // Hier folgen die Variablen des Singletons (nicht static!).

      // Nun kommen die Public-Methoden, über die auf das Singleton zugegriffen wird,

      // und schlussendlich noch die (privaten) Methoden, die die Implementierung enthalten.

      // Wichtig: Methoden, die auf Instanz-Variablen zugreifen, müssen mit entsprechenden Mitteln
      // synchronisiert werden, da es das Singleton nur einmal gibt und die Variablen somit automatisch global sind
      // und von mehreren Threads gleichzeitig darauf zugegriffen werden kann.

 }
  public final class Singleton {

      /** Private Klasse, einzige Instanz von Singleton wird beim Laden von Holder erzeugt. */
      private static class Holder {
          private static final Singleton INSTANCE = new Singleton();
      }

      /** Konstruktor ist privat, darf nicht von außen aufgerufen werden. */
      private Singleton() {}

      /** Statische Methode „getInstance()“ liefert die einzige Instanz der Klasse zurück. */
      public static Singleton getInstance() {
          return Holder.INSTANCE;
      }

 }

In this way, other static methods can be Singletoncalled by or constants defined in this can be referenced without INSTANCEalready generating them.

Implementation in Perl

The instance method returns $ instance or initializes it beforehand if this has not already been done.

package My::Singleton;

use strict; use warnings;

my $instance;

sub instance() {
        return $instance or $instance = bless {};
}

This can then be used with the following code:

use My::Singleton;

my $eins = My::Singleton->instance;   # eine neue Instanz
my $zwei = My::Singleton->instance;   # die gleiche Instanz

Thread safe

This is $instancealready created during the initialization of Singleton. This also :sharedmakes the example thread-safe.

package Singleton;

use strict; use warnings;

my $instance :shared = bless {};

sub instance() { return $instance; }

42;

With CPAN module

The CPAN module Class :: Singleton offers somewhat expanded functionality .

Implementation in PHP

From PHP version 5

<?php
 final class Singleton {

   // Anlegen der Instanz
   private static $instance = NULL;

   // Konstruktor privat, damit die Klasse nur aus sich selbst heraus instanziiert werden kann.
   private function __construct() {}

   // Diese statische Methode gibt die Instanz zurueck.
   public static function getInstance() {

       if (NULL === self::$instance) {
           self::$instance = new self;
       }
       return self::$instance;
   }
   // Klonen durch private Klonmethode von außen verbieten.
   private function __clone() {}
 }

 // Erzeugen einer Instanz der Klasse
 $singleton = Singleton::getInstance();
?>

Implementation in Python

From Python version 2.2

  class Singleton(object):
      def __new__(type, *args):
          # Falls es noch keine Instanz dieser Klasse gibt, wird eine erstellt und in _the_instance abgelegt.
          # Diese wird dann jedes Mal zurückgegeben.
          if not '_the_instance' in type.__dict__:
              type._the_instance = object.__new__(type)
          return type._the_instance

      def __init__(self):
          if not '_ready' in dir(self):
              # Der Konstruktor wird bei jeder Instanziierung aufgerufen.
              # Einmalige Dinge wie zum Beispiel die Initialisierung von Klassenvariablen müssen also in diesen Block.
              self._ready = True

Borg pattern

There are also several approaches to the singleton design pattern in Python. An implementation of the monostate principle is also known as the Borg pattern :

class Borg(object):
    _shared = {}
    def __new__(cls,*args,**kwargs):
        inst = object.__new__(cls)
        inst.__dict__ = cls._shared
        return inst

Implementation in Visual Basic .NET

The following implementation is thread safe.

  Public Class Singleton

    ' Variable zur Speicherung der einzigen Instanz
    Private Shared instance As Singleton = Nothing

    ' Hilfsvariable für eine sichere Threadsynchronisierung.
    Private Shared ReadOnly mylock As New Object()

    ' Konstruktor ist privat, damit die Klasse nur aus sich selbst heraus instanziiert werden kann.
    Private Sub New()
        '
    End Sub

    ' Diese Shared-Methode liefert die einzige Instanz der Klasse zurück.
    Public Shared Function GetInstance() As Singleton
        SyncLock (mylock)
            If instance Is Nothing Then
                instance = New Singleton
            End If
        End SyncLock

        Return instance

    End Function

  End Class

  ' Zugriff über Dim s As Singleton = Singleton.GetInstance()

Individual evidence

  1. Paul DiLascia: Singleton class private constructor C # singleton class, and More. In: MSDN Magazine. Microsoft, accessed April 13, 2013 .
  2. MethodImplOptions enumeration. In: MSDN . Microsoft , accessed April 13, 2013 .
  3. ^ Judith Bishop: C # 3.0 Design Patterns . O'Reilly, 2008, ISBN 978-0-596-52773-0 (English).
  4. ^ Jon Skeet: Implementing the Singleton Pattern in C #. Retrieved April 13, 2013 .
  5. Joshua Bloch: Creating and destroying Java object. InformIT, April 16, 2008, accessed April 13, 2013 .
  6. ^ Boris Brock: A Reusable Base Class for the Singleton Pattern in C #. In: Code Project . April 5, 2013, accessed April 13, 2013 .
  7. ^ Martin Lapierre: Generic Singleton Pattern using Reflection, in C #. In: Code Project . June 9, 2009, accessed April 13, 2013 .
  8. Joshua Bloch: Effective Java . 2nd Edition. Addison-Wesley Professional, 2008, ISBN 978-0-13-277804-6 (English, books.google.at [accessed on January 26, 2014]).
  9. ^ Peter Haggar: Double-checked locking and the Singleton pattern. In: Java Library. IBM, accessed April 13, 2013 .
  10. Tim Lindholm, Frank Yellin: The JavaTM TM Virtual Machine Specification . 2nd Edition. S. Section 2.17.4 ( docs.oracle.com [accessed January 22, 2007]). docs.oracle.com ( Memento of the original from April 14, 2012 in the Internet Archive ) Info: The archive link was inserted automatically and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice.  @1@ 2Template: Webachiv / IABot / docs.oracle.com