SINGLE INSTANCE
Singleton pattern restricts the instantiation of a class to a single instance. A private constructor hides the class for outside.
class LearningApp {
public static void main(String[] args) {
MyClass A = MyClass.getInstance();
MyClass B = MyClass.getInstance();
MyClass C = new MyClass();
// Error: The constructor MyClass() is not visible
}
}
class MyClass {
private static final MyClass INSTANCE = new MyClass();
private MyClass() {} // private constructor
public static MyClass getInstance() {
return INSTANCE;
}
}
The static keyword is used for unique initialization.
A static class is not automatically a Singleton class.
class LearningApp {
public static void main(String[] args) {
Obj o1 = new Obj();
System.out.println( o1.getInstances() );// count = 1
Obj o2 = new Obj();
System.out.println( o2.getInstances() );// count = 1
}
private static class Obj {
private int count = 0; // it should be declared static
private Obj() {
count++; // without static it is always 1
}
public int getInstances() {
return count;
}
}
}
Questions and answers
With Singleton Pattern a class can be instantiated
- a) only once
- b) many times
A private class can be instantiated
- a) no, it cannot be instantiated
- b) yes, but only from the same package
A class with a private constructor can't be instantiated
- a) true
- b) false
If we want unique instantiation for a class
- a) we use static keyword
- b) we use Singleton pattern
A Singleton class has no public constructor
- a) false
- b) true