参考wiki上 Example -> Java部分的Logger实例,这个实现方法比之前我在GODU中的实现更好,因为Logger的实现类只要实现自己对消息的处理即可,完全不必关心其他事情,而我的实现里AuthUnit实现了抽象类AFuncUnit,在其processRequest方法处理处理消息,还要加上向后传递的动作:
next.writeMessage(msg);
Logger之所以能实现“自动”向后传递,是因为客户处理消息时调用的是Logger.message(msg)方法,而实际处理消息的方法是writeMessage(msg)方法,message(msg)方法分两步:首先是处理消息,然后是向后传递:
next.message(msg);
它使用的是抽象父类的message方法,而不是直接调用next.writeMessage(msg)方法。
writeMessage被子类实现,所以是abstract protected,而message是对外接口,所以是public。
完整代码:
package chainofresp;
abstract class Logger {
public static int ERR = 3;
public static int NOTICE = 5;
public static int DEBUG = 7;
protected int mask;
// The next element in the chain of responsibility
protected Logger next;
public void setNext(Logger log) {
next = log;
}
public void message(String msg, int priority) {
if (priority <= mask) {
writeMessage(msg);
}
if (next != null) {
next.message(msg, priority);
}
}
abstract protected void writeMessage(String msg);
}
class StdoutLogger extends Logger {
public StdoutLogger(int mask) {
this.mask = mask;
}
protected void writeMessage(String msg) {
System.out.println("Writing to stdout: " + msg);
}
}
class EmailLogger extends Logger {
public EmailLogger(int mask) {
this.mask = mask;
}
protected void writeMessage(String msg) {
System.out.println("Sending via email: " + msg);
}
}
class StderrLogger extends Logger {
public StderrLogger(int mask) {
this.mask = mask;
}
protected void writeMessage(String msg) {
System.err.println("Sending to stderr: " + msg);
}
}
public class ChainOfResponsibilityExample {
private static Logger createChain() {
// Build the chain of responsibility
Logger logger = new StdoutLogger(Logger.DEBUG);
Logger logger1 = new EmailLogger(Logger.NOTICE);
logger.setNext(logger1);
Logger logger2 = new StderrLogger(Logger.ERR);
logger1.setNext(logger2);
return logger;
}
public static void main(String[] args) {
Logger chain = createChain();
// Handled by StdoutLogger (level = 7)
chain.message("Entering function y.", Logger.DEBUG);
// Handled by StdoutLogger and EmailLogger (level = 5)
chain.message("Step1 completed.", Logger.NOTICE);
// Handled by all three loggers (level = 3)
chain.message("An error has occurred.", Logger.ERR);
}
}
/
The output is:
Writing to stdout: Entering function y.
Writing to stdout: Step1 completed.
Sending via e-mail: Step1 completed.
Writing to stdout: An error has occurred.
Sending via e-mail: An error has occurred.
Writing to stderr: An error has occurred.
/