khaleel. Powered by Blogger.

What-is-singleton-design-pattern?

Thursday 2 June 2011

The Singleton Design Pattern is a Creational type of design pattern which assures to have only a single instance of a class, as it is necessary sometimes to have just a single instance.The examples can be print spooler,database connection or window manager where you may require only a single object.

In a Singleton design pattern,there is a public, static method which provides an access to single possible instance of the class.The constructor can either be private or protected.

public class SingletonClass {
private static SingletonClass instance = null;
protected SingletonClass() {
// can not be instantiated.
}
public static SingletonClass getInstance() {
if(instance == null) {
instance = new SingletonClass();
}
return instance;
}
}


In the code above the class instance is created through lazy initialization,unless getInstance() method is called,there is no instance created.This is to ensure that instance is created when needed.

public class SingletonInstantiator {
public SingletonInstantiator() {
SingletonClass instance = SingletonClass.getInstance();
SingletonClass anotherInstance =
new SingletonClass();
...
}
}


In snippet above anotherInstance is created which is a perfectly legal statement as both the classes exist in the same package in this case 'default', as it is not required by an instantiator class to extend SingletonClass to access the protected constructor within the same package.So to avoid even such scenario, the constructor could be made private.

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
Promote Your Blog

About This Blog

This blog is for java lovers

Total Pageviews

About Me

khaleel-bapatla
BAPATLA, ap, India
simple and honest
View my complete profile

  © Blogger template On The Road by Ourblogtemplates.com 2009

Back to TOP