Java Reference
In-Depth Information
Note the different aspects at play here. First of all, the static final field is immediately initialized
to contain the single singleton object (which cannot be changed afterward due to being final).
Second, direct instantiation of objects is prohibited by making the constructor private. Third, the
single instance is accessed calling the public static getInstance() method.
This way of defining a singleton class is called “eager initialization,” as the single instance gets
created no matter whether it will be used during the execution of the program. The alternative,
called “lazy initialization,” first sets the INSTANCE (nonfinal, then) field to null and initializes it the
first time the getInstance() method is called. Using this approach, however, can introduce subtle
bugs in multithreaded Java programs (where multiple tasks are executed in parallel) if not imple-
mented correctly, so it is not advisable.
Another interesting, less‐used way to define a singleton in Java is by using an enum type:
public enum Singleton {
INSTANCE;
// Other public methods follow here
}
This method is preferred by some, as it takes advantage of Java's guarantee that enum values are
instantiated only once in a Java program, are globally accessible, and are instantiated lazily without
potential issues regarding multithreading. You use the singleton enum as follows:
Singleton.INSTANCE.theSingletonMethod();
Now that you know how the singleton pattern works, it is time for a word of advice: this pattern is
one of the most overused and badly used design patterns out there. The reason for this is easy to see:
the singleton pattern provides an easy way out whenever you want to introduce global variables or
state in your program. Why is this a bad thing? By allowing global state in your program, you allow
any other parts of your program to access and modify this at any time, making these programs very
hard to test and debug when something goes wrong (who modified the singleton in a bad manner?).
In many real‐life cases, less experienced programmers will resort to using singletons whenever they
feel that they need a “manager” class to store some centralized information, perform some central-
ized task, or babysit other objects. For example, take a look at the following extreme case:
public class Account {
private String name;
private double amount;
public String getName() {
return name;
}
public double getAmount() {
return amount;
}
public void setName(String name) {
this.name = name;
Search WWH ::




Custom Search