责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。
思考: 责任链中的每个处理器都包含了下一个处理器的引用, 并且将需要处理的信息, 不停的传下去, 但是我怀疑会不会有栈溢出的问题
package day0320.ChainOfResponsibilityPattern;
public class Demo{
public static void main(String[] args){
AbstractLogger logger = new ConsoleLogger();
AbstractLogger error = new ErrorLogger();
AbstractLogger file = new FileLogger();
AbstractLogger mylogger = new MyLogger();
logger.setNextLogger(error);
error.setNextLogger(file);
file.setNextLogger(mylogger);
// 写一条日志, 日志级别高于或者等于指定级别的日志器才需要写, 低于指定级别的日志器不需要写
logger.logMessage("jack's doudou is a big bad guy"
, AbstractLogger.ALL);
}
}
abstract class AbstractLogger{
public static int CONSOLE = 3;
public static int ERROR = 2;
public static int FILE = 1;
public static int ALL = Integer.MIN_VALUE;
private int level = 0;
AbstractLogger nextLogger;
public void setNextLogger(AbstractLogger nextLogger){
this.nextLogger = nextLogger;
}
public int getLevel(){
return level;
}
public void setLevel(int level){
this.level = level;
}
public AbstractLogger getNextLogger(){
return nextLogger;
}
void logMessage(String msg, int level) {
if (this.getLevel() >= level) {
write(msg);
}
if(nextLogger != null ){
nextLogger.logMessage(msg, level);
}
}
// 是logmessage的底层支持
abstract void write(String msg);
}
class ConsoleLogger extends AbstractLogger {
int level = AbstractLogger.CONSOLE;
public ConsoleLogger(){
}
@Override
public int getLevel(){
return level;
}
@Override
public void setLevel(int level){
this.level = level;
}
void write(String msg) {
System.out.println("[CONSOLE] " + msg);
}
}
class ErrorLogger extends AbstractLogger {
int level = AbstractLogger.ERROR;
@Override
public int getLevel(){
return level;
}
@Override
public void setLevel(int level){
this.level = level;
}
public ErrorLogger(){
}
void write(String msg) {
System.out.println("[ERROR] " + msg);
}
}
class FileLogger extends AbstractLogger {
@Override
public int getLevel(){
return level;
}
@Override
public void setLevel(int level){
this.level = level;
}
int level = AbstractLogger.FILE;
public FileLogger(){
}
void write(String msg) {
System.out.println("[FILE] " + msg);
}
}
class MyLogger extends AbstractLogger {
int level = 1;
@Override
public int getLevel(){
return level;
}
@Override
void write(String msg){
System.out.println("输出到ActiveMQ消息队列中: " + msg);
System.out.println("然后: ");
System.out.println("写在我自己的小本本上: " + msg);
}
}