Reputation:
If we have a singleton class, say:
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
Now we want to do the classic work. Add some global variables and methods, to simplify just think about getters. Imagine we need to global variables, say str1 and str2:
This two variables and their getters must be static or the fact that we are forcing this class to be a singleton is enough to ensure that only one instance of the class wil exists?
To be more precise:
private String str1;
private String str2;
VS
private static String str1;
orivate static String str2;
AND
public String getStr1();
public String getStr2();
VS
public static String getStr1();
public static String getStr2();
Upvotes: 3
Views: 648
Reputation: 17548
The private constructor will enforce having only one instance at a time. You should still follow standard OOP principles .
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
private String str1;
private String str2;
public String getStr1() { return str1; }
public String getStr2() { return str2; }
}
Upvotes: 1