Singleton pattern
Definition: At any point of time we ensure that there is only object created for the class
Example:
participant classes:
- Singleton.java
- SingletonClient.java(client)
Diagram:
- This class includes a static member variable singleton with private scope
- the constructor is private so that no one can instantiate it
- we have a getCurrentInstance() method to instantiate the class. If the instance is already available then the instance is returned to the caller otherwise it is newly created
public class Singleton { private static Singleton singleton = null; private Singleton(){ } public static synchronized Singleton getCurrentInstance(){ if(singleton == null){ return new Singleton(); } else{ return singleton; } } public void sayHello(){ System.out.println("Hello"); } }
SingletonClient.java
use getCurrentInstance() method to get the instance of Singleton class and use it.
public class SingletonClient { public static void main(String[] args) { Singleton singleton = Singleton.getCurrentInstance(); singleton.sayHello(); } }
contract:
cannot instatiate more than once.
getCurrentInstance() return only one instance at any point of time