Java Reference
In-Depth Information
how the class is used (i.e., not a global point of access). This is a simple mechanism that's somewhat
underused.
Providing a global point of access to an instance is the second and often the main reason that singletons
are used. This concept makes it easy to reach for an object that's utilized in many places, but sometimes
in places where you don't want it to be used. So what options are there to keep things organized?
In some cases, you can choose to pass in the object you need as an argument to the methods that
need it. However, it can be argued that many objects don't it well in the argument list of a method.
For instance, when every method that's added to a log file also has a Log object in its argument list,
things get messy quickly.
NOTe In many cases, singletons pop up for things that have to be used
and accessed throughout a codebase. Logging is a traditional example. This
concept is called “cross‐cutting concerns,” and an alternative programming
paradigm—aspect‐oriented programming—was designed to address these
concerns. Libraries exist to bring aspect‐oriented features to Java, but their
use is not very widespread. Refactoring your code and trying to keep things as
neat as possible is the preferred way to go.
For “global” objects that only have to be accessed by a class and its subclasses, it is a good idea
to make the singleton object a field of the superclass, together with a private method such as
getObjectOfInterest() . The subclasses derived from the superclass then have access to the object
they need, without the object being accessible to other classes and their instances.
For global classes that offer a set of utility functions, consider making the class and all its methods
static to build a “static utility class.” In many cases, this is a better approach and one you'll see
in many Java programs. Many third‐party libraries offer classes ending in “ Utils ” ( FileUtils ,
StringUtils , and so on), and they contain nothing else but public static helper methods. Although
these methods are also globally accessible, the class itself does not contain any state. Naturally, this
point only holds when you do not define static variables in the helper class that's being modified by
the methods. The only reason why static utility classes should contain static fields is to define help-
ful constants (such as the static double PI variable in the Math class). If you do decide to create a
static utility class, however, always keep in mind the earlier example, and try to encapsulate as much
behavior as possible in the appropriate classes themselves whenever possible (no AccountUtils !).
static utility class or singleton?
You might be wondering what the difference is between the following two ways to
define a singleton class in Java:
// As a static utility class:
public class Singleton {
private static int A = 0;
public static int get() {
return A;
continues
 
Search WWH ::




Custom Search