Home » JAVA/J2EE » Archive by category 'Design Patterns'
Creational Patterns – Abstract Factory Pattern

Today we are going to see one of the design patterns abstract factory. Its one level of abstraction higher than factory pattern.The main use of Abstract Factory Patten is that is isolates the concrete classes which are generated. (more…)

Singletons in Java

Singletons are the design pattern when you want only one instance of a class created. You make the constructor private, and give access to the instantiated object via a static instance method that creates the object if it has not been created already.
The singleton class is threadsafe lazy instantiation. I hope many would be knowing on lazy instantiation. With lazy instantiation, a program refrains from creating certain resources until the resource is first needed — freeing valuable memory space. In lame man words, loading the resource only when its needed.
[codesyntax lang="java5"]
public class YourSingletonClass{
private static YourSingletonClassinstance = new YourSingletonClass();
public static YourSingletonClass getInstance(){
return instance;
}
private YourSingletonClass(){
}
}
[/codesyntax]
How do we ensure only one the same instance is returned?

We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.