I am working in singleton design pattern. I am using one static variable as member variable for my class. According to my code It is creating more than one instance even though i am I made singleton class. Please help me Is it correct way to do things? //This is my code
public class MySingleton {
public static MySingleton instance = null;// new MySingleton();
static int count;
private MySingleton() {
count++;
}
public static MySingleton getInstance() {
if (instance == null) {
synchronized (MySingleton.class) {
instance = new MySingleton();
}
}
return instance;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MySingleton news = new MySingleton().getInstance();
System.out.println(news.count);
MySingleton news1 = new MySingleton().getInstance();
System.out.println(news1.count);
MySingleton news2 = new MySingleton().getInstance();
System.out.println(news2.count);
}
}