Background A scavenger hunt question from the assigned readi
Solution
By seeing the code in the question above, there is a pattern implemented here.
JAVA SINLETON PATTERN
To implement Singleton pattern, we have different approaches but the common concepts followed here are as below
-> There is a private constructor to restrict instantiation of the class from other classes
-> private static variable of the same class that is the only instance of the class
-> Public static method that returns the instance of the class. This is the only global access point to outer world.
a) If line c is deleted, then the class is not a singleton pattern, object can be created anytime from any other class when we require to use and the static function present in the class is executed at the time of class loading and instance is created even though client application might not be using it.
b)
class X {
private int i;
private X r = new X();
static X factory(int v){
r.i = v;
return r;
}
}
c) If static is omitted, then
X test = new X();
X a = test.factory(3);
d) Removing a private from line c will create object of X in any other class using
X a = new X();
and also, at the time of loading of the class, it will call a factory method, which will create an instance of X. If class is not called outside the class, the instantiated object will be of no use.
