The most successful people in any walks of lives may not be the most talented ones but are definately the most passionate & dedicated ones.

Monday, August 23, 2010

SingleTon Design Pattern Explained

Definition
One instance of a class or one value accessible globally in an application.

Benefits
Well control the instantiation of a class.
Access to the instance by the way you provided.

Usage
Single window manager
Single printer spooler
Single Input/Output socket
Single log-writer

Sample implementation
**************************class definition starts here**************************
/**
* Purpose :- to implement SingleTon Design Pattern
* Few important points:-
* (a) constructor marked as private
* (b) getSingleTonInstance() is marked as synchronized
* (c) static member & method is used to hold & retrieve (respectivly) the instance.
*/
package singleTonPattern;

/**
* @author Vinay K Mudgil
* @date Aug 23rd 2010
*
*/
public class SingleTonImpl {

/*
* private class-level (static) variable to hold the single instance created.
* initially intialized to null to ensure that object gets created only when its required.
*/
private static SingleTonImpl SingleTonObj = null;



/*
* Private constructor to ensure that this class can't be instantiated via outside [using a new keyword]
*/
private SingleTonImpl() {
//Do nothing -- not required to perform any functions
}


/*
* ----A public class-level method which is visible to all but ensures that only a single object of SingleTonImpl class is created.
* ----This is marked as synchronized to ensure two threads accessing simultaneously shouldn't aceess this and thus eradicating
* possiblity of have more than one object.
*/
public synchronized static SingleTonImpl getSingleTonInstance() {
if (SingleTonObj == null)
SingleTonObj = new SingleTonImpl();

return SingleTonObj;
}



/*
* Overriding clone() method to ensure that object cloning isn't allowed and multiple objects can't be created.
*/
public Object clone() throws CloneNotSupportedException {
//throw appropriate exception
throw new CloneNotSupportedException();
}


}
**************************class definition ends here**************************


Please feel free to comment on this writeup and let me know if nay mistakes you find here in the code snippet or in any of the concepts. Happy to learn !!!

Thank you & keep visiting for more information.
--Vinay

1 comment:

  1. Nice post. Just to add Singleton can be much easily represented in java Enum e.g.

    public enum Singleton{
    INSTANCE;
    }

    I have also shared my view as 10 Singleton pattern interview question in Java you may find interesting.

    ReplyDelete