Creational Design Patterns provide solution to instantiate an object in the best possible way for specific situations. Following design patterns come under this category.
Singleton pattern ensures that only one object of a particular class is ever created.
Sometimes it’s important for some classes to have exactly one instance. There are many objects we only need one instance of them and if we, instantiate more than one, we’ll run into all sorts of problems like incorrect program behavior, overuse of resources, or inconsistent results.
Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.
There are only two points in the definition of a singleton design pattern:
This sequence diagram shows how simple it is for a client to get an instance of the Singleton.
Usage of Singleton design pattern:
Java
// file Singleton.java class Singleton { private static Singleton instance; private Singleton() {} public static synchronized Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } public void doSomething() { System.out.println("Singleton"); } // serialization protected Object readResolve() { return getInstance(); } } // file Demo.java public class Demo { public static void main(String[] args) { Singleton object = Singleton.getInstance(); object.doSomething(); } }
Python 3
Create Singleton using metaclass.
class SingletonType(type): instance = None def __call__(cls, *args, **kw): if not cls.instance: cls.instance = super(SingletonType, cls).__call__(*args, **kw) return cls.instance class Singleton(object): __metaclass__ = SingletonType def do_something(self): print('Singleton') s = Singleton() s.do_something()