Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Monday, August 3, 2009

Basic Example Of Singleton

Hi friends,
Today I would like to give out an another program for singleton pattern.

Logic:

Only one object can be created. Here suppose if another object is created I have assigned its reference to point to the Object already created.
So, here only one object would be created, but if even if another user tries to create another object then his reference would be same.You will understand this is more detail with the following example.

Code:

public class SingletonSampleGood {
static int flag = 0;
private static SingletonSampleGood chandraSample = null;
private String name;

private SingletonSampleGood() {
if (flag != 0) {
System.out.println("Singleton from chandra");

} else {

getInstance();
System.out.println("Flag Error");
}
}

public static SingletonSampleGood getInstance() {
if (chandraSample == null) {
flag = 1;

chandraSample = new SingletonSampleGood();
flag = 0;
} else {
System.out.println("Error");

return chandraSample;
}
return chandraSample;
}

public static void main(String[] args) {
SingletonSampleGood sample1 = SingletonSampleGood.getInstance();
System.out.println("Reference1 =" + sample1);
SingletonSampleGood chandraSample1 = SingletonSampleGood.getInstance();
System.out.println("Reference2 =" + chandraSample1);
}

}

Output:

Singleton from chandra
Reference1 =SingletonSampleGood@3e25a5
Error
Reference2 =SingletonSampleGood@3e25a5

So friends,
Hope you found my program useful in explaining the Singleton pattern concept. Hope it was useful to you.
Please give your suggestions for further improvement.

No comments: