Java Reference
In-Depth Information
// Pass command to next link in chain:
if (nextLoggerInChain != null)
nextLoggerInChain.logMessage(message);
}
// Method to be extended by subclasses
abstract protected void performLogging(String message);
}
Separate subclasses, such as ConsoleLogger , DatabaseLogger , FileLogger , and so on, log mes-
sages to a related target and pass the message to the next link in the chain. An example main
method might look like this:
public static void main(String[] args) {
Logger consoleLogger = new ConsoleLogger();
Logger emailLogger = new EmailLogger();
Logger databaseLogger = new DatabaseLogger();
consoleLogger.setNext(emailLogger);
emailLogger.setNext(databaseLogger);
// Send a message down the chain:
consoleLogger.logMessage("Log this message");
}
The chain‐of‐responsibility pattern is somewhat underappreciated in practice. In most cases, you'll
see examples like this one being solved by an implementation of the observer pattern (which you'll
see next). However, the chain‐of‐responsibility pattern is still mentioned here, for two reasons. The
first one is that this pattern also defines an order of responsibility. For a logging system, this is not
important, but for other systems, it can be useful to establish an ordering, with the first objects in
the chain getting a chance to handle the incoming message or object (and potentially modify it)
before passing it on. The second reason entails this “passing on” behavior. In most cases where this
pattern is useful, you'll code it in such a way that an object in the chain will only pass on an incom-
ing object when the current link is unable to do anything useful with it. Once a link that can handle
the incoming object is found, the processing stops there.
Observer Pattern and Model‐View‐Controller Pattern
The observer pattern describes a framework in which a particular object (the subject) maintains a
list of dependents (observers) and notifies them of any important changes.
In Java, this pattern can be implemented in different ways. The first one is by using Java's built‐in
java.util.Observable class and the java.util.Observer interface. Observable defines the fol-
lowing methods your classes can override:
void addObserver(Observer o)
void deleteObserver(Observer o)
void deleteObservers()
int countObservers()
 
Search WWH ::




Custom Search