Java Reference
In-Depth Information
continued
}
public static void set(int a) {
A = a;
}
}
// A single instance of a class:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private int A;
private Singleton() {
A = 0;
}
public static Singleton getInstance() {
return INSTANCE;
}
public int get() {
return A;
}
public void set(int a) {
A = a;
}
}
Ignoring the fact that using static variables to keep state is not good practice, both
of these classes seem to achieve the same end, although there is a subtle difference.
Consider a Logger singleton class with a log(String message) method.
Imagine that, at first, this method just shows a message on the console, but later
on, you want to add functionality to log a file and retain the ability to choose at
runtime which of the two implementations to use. With a static utility class, you
would have to resort to a check in the log method to see which path of execu-
tion to follow. If the singleton contains more methods, the check has to be added
to every method, reducing maintainability and introducing redundancy. With the
non‐static singleton object, you can make the log method abstract and create two
subclasses— ConsoleLogger and FileLogger . You can then determine the right
object to assign as the instance, without modifying any other code. The second
way is thus better practice from an Object-Oriented Programming viewpoint. That
said, remember that whenever you are defining a utility class without its own state
and thus holding a collection of simple utility functions, it is better to define it as a
static class.
To conclude this discussion on the singleton pattern, consider the following guidelines:
Always check whether you actually need a separate class or whether the behavior belongs in
an existing class.
When you need a globally accessible list of utility methods, use a static utility class without
modeling any state (static variables that are being changed by the class methods).
Search WWH ::




Custom Search