Singleton

ImprimirCitar
A class UML diagram that implements the singleton pattern.

In software engineering, singleton or single instance is a design pattern that allows you to restrict the creation of objects belonging to a class or the value of a type to a single object.

It is intended to ensure that a class has only one instance and to provide a global access point to it.

The singleton pattern is implemented by creating a method in our class that creates an instance of the object only if one does not already exist. To ensure that the class cannot be instantiated again, the scope of the constructor is regulated (with access modifiers such as protected or private).

Pattern instrumentation can be tricky in multi-threaded programs. If two threads are trying to create the instance at the same time and the instance doesn't exist yet, only one of them should succeed in creating the object. The classic solution to this problem is to use mutex in the create method of the class that implements the pattern.

The most common situations for applying this pattern are those in which said class controls access to a single physical resource (such as the mouse or a file open exclusively) or when certain types of data must be available for all other application objects.

Critics regard the singleton as an anti-pattern used in scenarios where it is not beneficial, introduces unnecessary restrictions where a single instance of a class is not really required, and adds global state in the application.

The singleton pattern provides a single global instance because:

  • The class itself is responsible for creating the only instance. Through his construction method.
  • It allows global access to such an instance through a class method.
  • Declare the class builder as private so that it is not directly instanceable.
  • Being internally self-referenced, in languages like Java, the garbage collector does not act.

Example Implementation

ActionScript 3

An implementation of the singleton pattern in ActionScript is as follows:

public class Singleton{ private static var instance:Singleton; private static var allowInstance:Boolean; public function Singleton(){ if(!allowInstance throw new Error("You must use getInstance()"); !else{ trace("A singleton instance was initialized"); ! ! public static function getInstance():Singleton{ if(instancenull allowInstance=bar; instance= new Singleton(); allowInstance=false; !else{ trace("The existing instance is returned."); ! return instance; !!

Autoit

An implementation of the singleton pattern in Autoit is as follows:

# Include .Misc.au3if _("test",1) = 0 Then Msgbox(0,"Warning","An occurence of test is already running") ExitEndIfMsgbox(0,"OK","the first occurence of test is running")

C#

A correct example of safe, lazy initialization in multi-threaded environments in C# would be:

public class Singleton{ // static variable for instance, you need to use a lambda function as the builder is private private static readonly Lazy.Singleton instance = new Lazy.Singleton(() = 2005 new Singleton()); // Private builder to avoid direct instance private Singleton() { ! // Property to access the instance public static Singleton Instance { get { return instance.Value; ! !!// Test classpublic class Test{ private static void Main(string[] args) { //Singleton s0 = new Singleton(); //Error Singleton s1 = Singleton.Instance; Singleton s2 = Singleton.Instance; if(s1s2) { // Misma instance ! !!

C++

A possible solution in C++ (known as the Meyers singleton) in which the singleton is a static local object (note that this solution is not thread-safe):

template template template template .class Tclass Singleton{ public: static T" Instance() { static T InstantSingleton; //asumir T has a default builder return InstantSingleton; !};class Singleton : public Singleton.Singleton{ friend class Singleton.Singleton; //to give access to the private builder of SoloUno //..define here the rest of the interface};

D

A possible implementation in D would be:

Final class Singleton { private static Singleton instance; static this() { instance = new Singleton(); ! static Singleton opCall() { return instance; !!car s1 = Singleton();car s2 = Singleton();assert(s1  s2);

Delphi

This implementation has been taken from [1] and is based on the override of the NewInstance and FreeInstance methods that inherits from the TObject class, the mother of all. the objects in Embarcadero Delphi.

type TSingleton = class public class function NewInstance: TObject; override; procedure FreeInstance; override; class function RefCount: Integer; end;var Instance : TSingleton = nil; Ref_Count : Integer = 0;

And its implementation would be like this:

procedure TSingleton.FreeInstance;begin Dec( Ref_Count ); if ( Ref_Count = 0 ) then begin Instance := nil; // Destroy private variables here inherited FreeInstance; end;end;class function TSingleton.NewInstance: TObject;begin if ( not Assigned( Instance ) ) then begin Instance := inherited NewInstance; // Initialize private variables here, like this: // TSingleton(Result)Variable:= Value; end; Result := Instance Inc( Ref_Count );end;class function TSingleton.RefCount: Integer;begin Result := Ref_Count;end;

Java

The most common implementation in the Java programming language is the following:

public class Singleton { private static Final Singleton INSTANCE = new Singleton(); // The private builder does not allow a default builder to be generated. // (with same access modifier as class definition)  private Singleton() {cHFFFF} public static Singleton getInstance() { return INSTANCE; !!

A correct example of lazy initialization. This is left to discuss a common error in Java by not taking method synchronization into account.

public class Singleton { private static Singleton INSTANCE = null; // Private builder suppresses  private Singleton(){} // synchronized creator to protect yourself from potential multi-hylo problems // other test to avoid multiple instance  private synchronized static void createInstance() { if (INSTANCE  null) { INSTANCE = new Singleton(); ! ! public static Singleton getInstance() { if (INSTANCE  null) createInstance(); return INSTANCE; !!

If we want to reduce the cost of synchronization, we check the instance before calling the "createInstance" method; it is also possible to do it in a single method as follows [2]:

 private static void createInstance() { if (INSTANCE  null) { // Only the synchronized zone is accessed // when the instance is not created synchronized(Singleton.class) { // In the synchronized zone it would be necessary to return // to check that the instance has not been created if (INSTANCE  null) { INSTANCE = new Singleton(); ! ! ! !

To ensure that the "single instance" from the singleton; the class should produce a non-clonable object:

// Thus you could clone the object and not have oneness.SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();

Then, cloning should be prevented by overriding the "clone" as follows:

// The "clone" method is overwritten by the following one that throws an exception:public Object clone() throws CloneNotSupportedException {throw new CloneNotSupportedException(); !

Another thing to keep in mind is that the methods (or the class) should be declared as: final so they can't be overridden.

There is another less known implementation, but with greater advantages within Java, which is the following:

public enum SingletonEnum { INSTANCE; int value; public int getValue() { return value; ! public void setValue(int value) { this.value = value; !!

This approach is thread-safe and serializable, guaranteed by the enum implementation.

Usage example:

public class EnumDemo { public static void main(String[] args) { SingletonEnum singleton = SingletonEnum.INSTANCE; System.out.println(singleton.getValue()); singleton.setValue(2); System.out.println(singleton.getValue()); !!

Javascript

An implementation of the singleton pattern in Javascript is as follows:

Singleton = function Singleton$constructor() { return { getInstance : function Singleton$getInstance() { return this; ! };}();

Objective C

A simple implementation of the Singleton pattern for the Objective C language is:

#import "Singleton.h" @implementation Singleton +(Singleton ) getInstance{ static Singleton singleton = nil; @synchronized(self if (!singleton) { singleton = [chuckles]self new]; ! ! return singleton;!@end

Another better way using GCD is:

+ (id)sharedInstance{ static dispatch_once_t pred = 0; __strong static id _sharedObject = nil; dispatch_once("pred, ^{ _sharedObject = [self alloc] init]; }); return _sharedObject;!

Perl

As usual in Perl, there is more than one way to do this. Among several possibilities, we can point out this:

[chuckles]Singleton.pm]package Singleton;my $singleton;sub new {my $class = shift;$singleton LICK= bless {cHFFFF}, $class;!...[chuckles]Foo.pl]Request Singleton;my $object1 = new Singleton;my $object2 = new Singleton;# The same object

PHP

An example of implementing the singleton pattern in PHP would be the following:

?class Singleton{ // Class Instance Container private static $instance = null; // Private builder, prevents the creation of instances via new private function __construct() { ! // Not allowed cloning private function __() { ! // Singleton method  public static function getInstance() { if (null  self::$instance) { self::$instance = new Singleton(); ! return self::$instance; !!

Python

The following is an example of a Singleton implementation in Python (it is also not safe in multi-threading):

class Singleton (object(c): instance = None def __(cls, args, **kargs(c): if cls.instance is None: cls.instance = object.__(cls, args, **kargs) return cls.instance#UsagemySingleton1 = Singleton()mySingleton2 = Singleton()#mySingleton1 and mySingleton2 are the same instanceassert mySingleton1 is mySingleton2

And another interesting possibility is to implement it as a metaclass:

class Singleton(type(c): def __init__(cls, name, bases, dct(c): cls.__instance = None type.__init__(cls, name, bases, dct) def __(cls, args, **kw(c): if cls.__instance is None: cls.__instance = type.__(cls, args,**kw) return cls.__instanceclass A: __metaclass__ = Singleton # Define here the rest of the interfacea1 = A()a2 = A()assert a1 is a2

Visual Basic.

An implementation of the singleton pattern in Visual Basic.NET is as follows:

Public Class Singleton Private Sub New() ' CONSTRUCTOR End Sub Private Shared instance As Singleton = Nothing Public Shared Function Function getInstant As Singleton If instance Is Nothing Then instance = New Singleton() End If Return instance End Function FunctionEnd Class

Related Patterns

  • Abstract Factory: They are often implemented by singleton, as they should normally be publicly accessible and there must be a single instance that controls the creation of objects.
  • Monostate: is similar to the singleton, but instead of controlling the instance of a class, it ensures that all instances have a common state, making all its members class.

Contenido relacionado

Air safety

Air safety is the set of measures that aim to find out the causes of each air accident in order to modify operating procedures and training, so as to avoid...

Ultrasound

The ultrasound also called ultrasonography or echosonography, is a diagnostic procedure used in hospitals and clinics that uses ultrasound to create two- or...

Second generation of computers

The main characteristics of the second generation computers...
Más resultados...
Tamaño del texto:
Copiar