Computer Science Design Patterns/Singleton

{{Computer Science Design Patterns/Page The term Singleton refers to an object that can be instantiated only once. Use the Singleton Design pattern if: In some applications, it is appropriate to enforce a single instance of an object, for example: window managers, print spoolers, database access, and filesystems.
 * mode={{{mode|reading}}}
 * page={{{page|{{SUBPAGENAME}}}}}
 * stage=25
 * stage date=29 Jan, 2014
 * stage comment=Add more illustrations.
 * previous=Proxy
 * next=State
 * content=
 * You need global access to a resource, like logging ...
 * You need only one instance of a utility class, do not want to create lots of objects.

Refresh Java object creation
In programming languages like Java, you have to create an instance of an object type (commonly called a Class) to use it throughout the code. Let's take for example this code: This can also be written in a single line to save space. At times, you need more than one instance of the same object type. You can create multiple instances of the same object type. Take for instance: Now that I have two instances of the same object type, I can use both  and   instances separately in my program. Any changes to  would not effect the   instance because both of them have been created in separate memory spaces. To see whether these objects actually are different we do something like this: The code returns  because both the objects are different. Contrary to this behavior, the Singleton behaves differently. A Singleton object type can not be instantiated yet you can obtain an instance of the object type. Let us create a normal object using Java. What we have done here is that we have created a class (object type) to identify our object. Within the braces of the class is a single method with the same name as that of the class (methods can be identified by the usage of parentheses at the end of their names). Methods that have the same name as that of the class and that do not have a return type are called Constructors in OOP syntax. To create an instance of the class, the code can not be much simpler. Note that to encourage the instantiation of this object, the constructor is called. The constructor as in this case can be called outside the class paranthesis and into another class definition because it is declared a public accessor while creating the Constructor in the above example. Now we will create the Singleton object. You just have to change one thing to adhere to the Singleton design pattern: Make your Constructor's accessor private. Notice the constructor's accessor. This time around it has been declared private. Just by changing it to private, you have applied a great change to your object type. Now you can not instantiate the object type. Go ahead try out the following code. The code returns an error because private class members can not be accessed from outside the class itself and in another class. This way you have disabled the instantiation process for an object type. However, you have to find a way of obtaining an instance of the object type. Let's do some changes here. The changes involve adding a static class field called   and a  method that can be accessible outside the scope of the class by using the name of the Class. To see how we can obtain the instance, lets code: This way you control the creation of objects derived from your class. But we have still not unearthed the final and interesting part of the whole process. Try getting multiple objects and see what happens. Unlike multiple instances of normal object types, multiple instances of a Singleton are all actually the same object instance. To validate the concept in Java, we try: The code returns  because both object declarations are actually referring to the same object. So, in summarizing the whole concept, a Singleton can be defined as an object that can not be instantiated more than once. Typically it is obtained using a static custom implementation.
 * Creating singleton object :

Singleton & Multi Threading
Java uses multi threading concept, to run/execute any program. Consider the class SingletonObject discussed above. Call to the method getInstance by more than one thread at any point of time might create two instances of SingletonObject thus defeating the whole purpose of creating the singleton pattern. To make singelton thread safe, we have three options: 1. Synchronize the method, which would look like: Synchronizing the method guarantees that the method will never be called twice at the same time. The problem with the above code is that 'synchronization' is expensive. 'Synchronization' checks will occur every time the function is called. Therefore, the above code should not be the first option. 2. Another approach would be to create a singleton instance as shown below: The above code will be much faster; once the singleton instance is created no synchronization is needed. It just returns the same instance reference. 3. Use static initialization block to create the instance. The JVM makes sure that the static block is executed once when the class is loaded.

Examples
In Java, the class  is a singleton. Its constructor is protected and you can get an instance by calling the  method.

Cost
Beware of this design pattern! It creates the same issues than the global variables in procedural programming so it can be hard to debug.

Creation
It can be expensive. You may have to refactor all the instantiations of the class, unless the class is new.

Maintenance
There is no additional cost.

Removal
This pattern can be easily removed as automatic refactoring operations can easily remove its existence.

Advises

 * Name the method  to indicate the use of the pattern to the other developers.
 * Use this design pattern for frozen data like configuration or external data. You will not have debugging issues.

Implementation
The Scala programming language supports Singleton objects out-of-the-box. The 'object' keyword creates a class and also defines a singleton object of that type. Singletons are declared just like classes except "object" replaces the keyword "class".

Traditional simple way using synchronization
This solution is thread-safe without requiring special language constructs:

Initialization on Demand Holder Idiom
This technique 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 when getInstance is called making this solution thread-safe without requiring special language constructs.

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" 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.

Singleton pattern in D programming language Or in this manner

Singleton pattern in PHP 5:

Private constructors are not available in ActionScript 3.0 - which prevents the use of the ActionScript 2.0 approach to the Singleton Pattern. Many different AS3 Singleton implementations have been published around the web.

A common way to implement a singleton in Objective-C is the following: If thread-safety is not required, the synchronization can be left out, leaving the  method like this: This pattern is widely used in the Cocoa frameworks (see for instance,,  ,   or  , to name but a few). Some may argue that this is not, strictly speaking, a Singleton, because it is possible to allocate more than one instance of the object. A common way around this is to use assertions or exceptions to prevent this double allocation. There are alternative ways to express the Singleton pattern in Objective-C, but they are not always as simple or as easily understood, not least because they may rely on the  method returning an object other than. Some of the Cocoa "Class Clusters" (e.g.,  ) are known to exhibit this type of behaviour. Note that  is not available in some Objective-C configurations, as it relies on the NeXT/Apple runtime. It is also comparatively slow, because it has to look up the lock based on the object in parentheses.

The simplest of all is: This example is thread-safe with lazy initialization. Example in C# 2.0 (thread-safe with lazy initialization) Note: This is not a recommended implementation because "TestClass" has a default public constructor, and that violates the definition of a Singleton. A proper Singleton must never be instantiable more than once. More about generic singleton solution in C#: http://www.c-sharpcorner.com/UploadFile/snorrebaard/GenericSingleton11172008110419AM/GenericSingleton.aspx

As described by James Heyworth in a paper presented to the Canberra PC Users Group Delphi SIG on 11/11/1996, there are several examples of the Singleton pattern built into the Delphi Visual Component Library. This unit demonstrates the techniques that were used in order to create both a Singleton component and a Singleton object:

The desired properties of the Singleton pattern can most simply be encapsulated in Python by defining a module, containing module-level variables and functions. To use this modular Singleton, client code merely imports the module to access its attributes and functions in the normal manner. This sidesteps many of the wrinkles in the explicitly-coded versions below, and has the singular advantage of requiring zero lines of code to implement. According to influential Python programmer Alex Martelli, ''The Singleton design pattern (DP) has a catchy name, but the wrong focus—on identity rather than on state. The Borg design pattern has all instances share state instead''. A rough consensus in the Python community is that sharing state among instances is more elegant, at least in Python, than is caching creation of identical instances on class initialization. Coding shared state is nearly transparent: But with the new style class, this is a better solution, because only one instance is created: Two caveats: To create a singleton that inherits from a non-singleton, multiple inheritance must be used. Be sure to call the NonSingletonClass's __init__ function from the Singleton's __init__ function. A more elegant approach using metaclasses was also suggested.
 * The __init__-method is called every time Singleton is called, unless cls.__init__ is set to an empty function.
 * If it is needed to inherit from the Singleton-class, instance should probably be a dictionary belonging explicitly to the Singleton-class.

In Perl version 5.10 or newer a state variable can be used. In older Perls, just use a global variable. If Moose is used, there is the MooseX::Singleton extension module.

In Ruby, just include the Singleton module from the standard library into the class.

In ABAP Objects, to make instantiation private, add an attribute of type ref to the class, and a static method to control instantiation.

program pattern_singleton. ***********************************************************************   * Singleton * =========   * Intent *   * Ensure a class has only one instance, and provide a global point * of access to it. *********************************************************************** class lcl_Singleton definition create private. public section. class-methods: get_Instance returning value(Result) type ref to lcl_Singleton. private section. class-data: fg_Singleton type ref to lcl_Singleton. endclass. class lcl_Singleton implementation. method get_Instance. if ( fg_Singleton is initial ). create object fg_Singleton. endif. Result = fg_Singleton. endmethod. endclass.

}}