Saturday, August 17, 2013

Singleton class and Static class

Singleton class and Static class

Difference between Singleton and Static class

The difference is singleton class might allow the implement interface, but not possible in static class.Using the single implementation (or derive from base class), it's just like another implementation.
Both should be implemented to be thread-safe

Singleton class example

A Singleton class allows to create a single instance only, that instance can be passed as parameter to other methods and it treated as a normal object.

public class MySingleTon {
private static MySingleTon myObj;
//Create private constructor
private MySingleTon(){

}

//Create a static method to get instance.
public static MySingleTon getInstance(){
if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}
}


Static class example
A Static class allows static method only.
class StaticExample
{
static void getInstance()
{
//Add code here
}
static void getData()
{
//Add code here
}
}

No comments:

Post a Comment