ALERT

Cisco CloudCenter: Get the Hybrid IT Advantage

Singleton

Definition - What does Singleton mean?

A singleton is a class that allows only a single instance of itself to be created and gives access to that created instance. It contains static variables that can accommodate unique and private instances of itself. It is used in scenarios when a user wants to restrict instantiation of a class to only one object. This is helpful usually when a single object is required to coordinate actions across a system.

The singleton pattern is used in programming languages such as Java and .NET to define a global variable. A single object used across systems remains constant and needs to be defined only once rather than many times.

Techopedia explains Singleton

A singleton is intended to provide only one instance of itself while facilitating a global point of access. Implementing a singleton pattern involves creating a class with a method that creates a new instance of the class. In order to implement a singleton pattern, principles of single instance and global access must be satisfied. The singleton class is like a global repository for an instance of itself, making the constructor private. Therefore, an instance outside the class cannot be created at all, and a singleton can contain only one instance. A singleton class instantiates itself and maintains that instance across systems.

Abstract factory, builder and prototype patterns can use singletons. Façade objects and static objects are often singletons. Singleton implementation requires a mechanism through which a class member can be accessed without having to create a class object and hold on to the value of class members among class objects. The steps involved in creating a singleton are as follows:

  1. The constructor is made private. This allows only the class to have access to the singleton.

  2. Example:
    class testdata
    {
    Private testdata ()
    {
    //… no-op for a singleton

  3. A single internal instance of the class is created using a method. The method is called an instance in this example. The method “instance” is used to initialize the class to access a single instance. The instance method is marked as static in this example to give all the threads consistent access. Outside the instance creation, the “lock” statement is used to control multithreaded access. This locks the instance creation to a single thread.

    Example:

    //Lazy creation of singleton internal instance
    Public static testdata Instance
    {
    Get
    {
    Lock(type of (testdata) )
    {
    If (_instance==null)
    _instance = testdata ();
    }
    Return _instance;
    }
    }
Share this: