Java Reference
In-Depth Information
projects, how you can use it yourself, and then common pitfalls you should watch out for. Don't
expect that all patterns will immediately be useful to you as a beginner, but you'll note that you will
feel a natural tendency toward them as you become more experienced.
This topic adopts the same structure and naming as the Gang of Four, dividing the patterns into
Creational, Structural, and Behavioral categories. Keep in mind that the focus here is on how each
pattern works and behaves in Java. The goal here is to show you the patterns that also teach you
how to make architectural design choices and how each choice allows certain freedoms and takes
away others. This section doesn't copy the description of the original patterns verbatim, as this
would not offer much value.
creational patterns
Creational patterns deal with object creation. Instead of creating objects directly, these patterns
offer more flexibility in terms of deciding which objects need to be created in a given case, mean-
ing that they offer alternatives for the following standard creation procedure in Java, as you've seen
throughout this topic:
House myHouse = new House();
Here, the singleton, static utility class, service provider (this pattern is not mentioned in the Gang of
Four book but is closely related to the singleton pattern), factory, and abstract factory patterns are
covered. The builder and prototype creational patterns are not discussed, as both of them are less
commonly applied in Java.
Singleton Pattern and Static Utility Class
Let's start with one of the most controversial object‐oriented patterns, the singleton pattern. (We'll
address the reasons behind its controversy later on.) The Gang of Four summarizes a design pattern
as follows:
Ensure a class has instance and provide a global point of access to that instance .
This pattern is useful whenever exactly one object is needed to coordinate certain actions. In Java,
an easy way to define a singleton class is as follows:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
// Other public methods follow here
}
You call the singleton 's methods as follows:
Singleton.getInstance().theSingletonMethod();
 
Search WWH ::




Custom Search