Thursday, June 12, 2008

singletone classes in Java

One of my most favourite design pattern(only known design pattern).

In many cases you may need to create a singleton classes. Oh I forgot to mentioned what is singleton class. We can create only one instance of a singleton class.


Now the question is how to create a singleton class. Its quite a simple and streight forward. We can create a singleton class by using static and private keyword.

Let me tell you about these keywords first.
private: when we make any method or variable as a private then that variable or method can be accessed through that class only.
static: When we make any method or variable as static then we can access that method or variable without creating instance of that class. And one more interesting thing about static method is that we can access only the static variables of that class.

Without wasting any time I am writing code for creating singleton class.

class MyClass{
private static Myclass instance;

private MyClass(){
}

public MyClass synchronized getMyClassObject(){
if(instance== null)
instance= new MyClass();
return instance;
}
}



In this case only one instance of MyClass can be created.

No comments: