There are three concepts being displayed here:
Tester class:
if (instance == null)
instance = new tester();
That's used when you wish to control the construction of an object. The variable instance
controls if new Tester()
will be called by boot()
.
This can be used to implement Lazy Initialization. That's the practice of delaying construction of an object until it is needed. It's typically used when construction is both expensive and not always needed. Here it is delayed until boot()
is called. Lazy Initialization is not only used for singletons. Some believe that using Lazy Initialization in java to create a singleton
is actually wrong because of how the class loader works. They claim it's a habit ported over from c++ where it made sense. As a pattern, singleton has been controversial enough that some call it an anti pattern.
Tester class:
public static tester instance;
boot()
, constructs a Tester
object, sets instance
to that object (Note: tester
should have been capitalized). The fact that instance
, which is of type Tester, resides in the
Testerclass means that
Testeris [**self referential**][7], like the nodes in a linked list. But, unlike nodes, because
instanceis
static, all
Testerobjects have the same copy of
instance`.
Because boot never puts what it constructs anywhere but in instance
, only one boot()
constructed Tester
object ever exists at any one time, so long as instance
is never copied anywhere. It easily could be, because it's public
.
So long as instance
is never set back to null
boot()
will construct a Tester
only once no matter how many times it's called. Since instance
is public
it could be set to null
at any time by anything that knows about Tester
. Doing so would allow boot()
to construct again and the old Tester
object would be forgotten (garbage collected).
Since Tester
s constructors have not been made private
there is no guaranty that Tester
is never constructed by something other than boot()
. That means there could still be many Tester
objects running around. But they all have one instance
in them that may or may not be themselves.
A classic singleton would have Lazy Initialization, be self referential, and be encapsulated in such a way that at most only one Tester
object would ever exist. However, There is nothing here that proves this was meant to be a singleton in the first place. This could be a construction optimization gone horribly wrong.