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
Hi, this would cause all threads to be blocked as synchronised method being static. It is significant performance hit and application may not scale if there are numerous singletons.
Is there any alternate? How about different class loaders?
Thanks, Kedar
check this for more info
http://www.oodesign.com/singleton-pattern.html
Pingback: Single object for Singleton pattern « They point the finger at me.. again!