Singleton provides a global access point
A singleton often has the characteristics of a registry or lookup service.
A singleton prevents the client programmer from having any way to create an object except the ways you provide.
You must make all constructors private.
You must create at least one constructor to prevent the compiler from synthesizing a default constructor.
You provide access through public methods.
Making the classfinal prevents cloning.
finalclass Singleton {
privatestatic Singleton s = new Singleton(47);
privateint i;
private Singleton(int x) {
i = x;
}
publicstatic Singleton getReference() {
return s;
}
publicint getValue() {
return i;
}
publicvoid setValue(int x) {
i = x;
}
}
publicclass SingletonPattern {
publicstaticvoid main(String[] args) {
Singleton s = Singleton.getReference();
String result = "" + s.getValue();
System.out.println(result);
Singleton s2 = Singleton.getReference();
s2.setValue(9);
result = "" + s.getValue();
System.out.println(result);
}
}