Chain-of-responsibility pattern: Difference between revisions

Content deleted Content added
Arch4ngel (talk | contribs)
Irrevelant to what the subject is. Even though they have the same name, it doesn't work the same way and can't help anyone understanding this design pattern.
Lathspell (talk | contribs)
Added self-invented Java example code.
Line 6:
 
''The article is originally from [[Perl Design Patterns Book]]''
 
== Examples ==
 
=== Java ===
The following Java code illustrates the pattern with the example of a logging class. Each logging handler decides if any action is to be taken at this log level and then passes the message on to the next logging handler. The output is:
Writing to debug output: Entering function x.
Writing to debug output: Step1 completed.
Writing to stderr: Step1 completed.
Writing to debug output: An error has occured.
Sending via e-mail: An error has occured.
Writing to stderr: An error has occured.
Note that this example should not be seen as a recommendation to write Logging classes this way.
 
import java.util.*;
'''abstract class Logger''' {
public static int ERR = 3;
public static int NOTICE = 5;
public static int DEBUG = 7;
protected int mask;
protected Logger next; ''// the next element in the chain of responsibility''
public Logger setNext(Logger l) { next = l; return this; }
abstract public void message(String msg, int priority);
}
'''class DebugLogger ''extends Logger''''' {
public DebugLogger(int mask) { this.mask = mask; }
public void message(String msg, int priority) {
if (priority <= mask) System.out.println("Writing to debug output: "+msg);
if (next != null) next.message(msg, priority);
}
}
'''class EMailLogger ''extends Logger''''' {
public EMailLogger(int mask) { this.mask = mask; }
public void message(String msg, int priority) {
if (priority <= mask) System.out.println("Sending via e-mail: "+msg);
if (next != null) next.message(msg, priority);
}
}
'''class StderrLogger ''extends Logger''''' {
public StderrLogger(int mask) { this.mask = mask; }
public void message(String msg, int priority) {
if (priority <= mask) System.out.println("Writing to stderr: "+msg);
if (next != null) next.message(msg, priority);
}
}
'''class ChainOfResponsibilityExample''' {
public static void main(String[] args) {
// building the chain of responsibility
Logger l = new DebugLogger(Logger.DEBUG).setNext(
new EMailLogger(Logger.ERR).setNext(
new StderrLogger(Logger.NOTICE) ) );
l.message("Entering function x.", Logger.DEBUG); ''// handled by DebugLogger''
l.message("Step1 completed.", Logger.NOTICE); ''// handled by Debug- and StderrLogger''
l.message("An error has occured.", Logger.ERR); ''// handled by all three Logger''
}
}