Java Reference
In-Depth Information
13.7.2
Decorator
The Decorator pattern deals with the problem of adding functionality to an existing object. We
assume that we want an object that responds to the same method calls (has the same interface)
as the existing object but has added or altered behavior. We may also want to add to the existing
interface.
One way this could be done is by inheritance. A subclass may override the implementation of
methods and add additional methods. But using inheritance is a static solution: once created,
objects cannot change their behavior.
A more dynamic solution is the use of a Decorator object. The Decorator is an object that en-
closes an existing object and can be used instead of the original (it usually implements the same
interface). Clients then communicate with the Decorator instead of with the original object
directly (without a need to know about this substitution). The Decorator passes the method calls
on to the enclosed object, but it may perform additional actions. We can find an example in
the Java input/output library. There, a BufferedReader is used as a Decorator for a Reader
(Figure 13.2). The BufferedReader implements the same interface and can be used instead
of an unbuffered Reader , but it adds to the basic behavior of a Reader . In contrast to using
inheritance, decorators can be added to existing objects.
Figure 13.2
Structure of the
decorator pattern
%XIIHUHG5HDGHU
5HDGHU
13.7.3
Singleton
A common situation in many programs is to have an object of which there should be only a sin-
gle instance. In our world-of-zuul game, for instance, we want only a single parser. If we write a
software development environment, we might want only a single compiler or a single debugger.
The Singleton pattern ensures that only one instance will be created from a class, and it pro-
vides unified access to it. In Java, a Singleton can be defined by making the constructor private.
This ensures that it cannot be called from outside the class, and thus client classes cannot create
new instances. We can then write code in the Singleton class itself to create a single instance
and provide access to it (Code 13.1 illustrates this for a Parser class).
Code 13.1
The Singleton pattern
public class Parser
{
private static Parser instance = new Parser();
public static Parser getInstance()
 
Search WWH ::




Custom Search