This is the
third approach of creating objects:
Singleton Property with private
constructor
A singleton
is a class which is instantiated only once. Making a class a singleton can
make it difficult to test its client, as its impossible to substitute a mock
implementation for a singleton unless it implements an interface that serves as
its type. There are few ways of implementing a singleton.
1. By keeping a private constructor
and exposing a static final member by one method:
public class SingletonTest {
public static final SingletonTest OBJECT= new SingletonTest();
private SingletonTest()
{
}
public void callMe() {
}
}
The object is initialized only once and called as SingletonTest.OBJECT. The
private constructor will make sure that there no other instance will be
created.
2. One more similar way is to keep a
public static factory method in addition to the above arrangement.
public class SingletonTest {
public static final SingletonTest OBJECT = new SingletonTest();
private SingletonTest() {
}
public static SingletonTest getInstance() {
return OBJECT;
}
public void callMe() {
}
}
Here also
the instance gets created only once. Thanks to the private constructor. As you can see the only difference from the
previous approach is the static method (which is in bold). We can call the
instance by SingletonTest.getInstance();
The advantage of this approach is it gives a clear idea that the
class is singleton.
{Courtesy: Effective Java - Joshua Bloch}
{Courtesy: Effective Java - Joshua Bloch}
No comments:
Post a Comment