Codementor Events

Singleton Design Pattern

Published Aug 26, 2018
Singleton Design Pattern

The Singleton Design Pattern is one of the simplist Design Patterns. It is part of the GoF (Gang of Four) Design Patterns and it falls into Creational Design Patterns category. It is supposed to ensure that at any given moment there is only one instance of an object alive in your application, hence the name Singleton, and provides a global point of access to it.

It also provides 'initialization on first use' since the object is not initialized until the moment it will be used for the first time.

But Why should we use it ?

  • Share common data accross the whole system
  • Reduce the headach of instantiating heavy objects
  • Can be used ti cache objects in-memory and reuse them when needed globally

Real life examples

  • Caching: Getting data or resources from a database can be an expensive operation, this pattern helps cache information you will need repeatedly all over your applciation and makes it available globally.

  • Invokign an API : By having a Service proxy as a Singleton the overhead of crating the service client every time can be reduced as it is time consuming.

  • Configuration : Sometimes sharing a common configuration throu the whole app is a must, a singleton can be very useful in this case insuring that all parts are accessing the same resource.

Code Examples

The following code examples, demonstrate simply how you can implement the singleton design pattern.

Java :

public class Singleton {
    private Singleton() {}

    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

C# :

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

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

Javascript :

var Singleton = (function () {
    var instance;
 
    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    }
 
    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();
Discover and read more posts from Smail OUBAALLA
get started
post comments1Reply
Federico Rossi
6 years ago

I wrote a post of singletons too https://www.codementor.io/federicorossi/get-a-low-cost-java-singleton-ne8m8zl30 (i swear that i didn’t saw the yours first) :D :D