1,什么是: 责任链? 链表式轮询机制==>询问a ( a-->询问b (b-->询问c (...
2,java 如何模拟: 此机制?===>类似log4j 日志打印体系,如:debug,error,info等级别,
若指定打印级别: error, 可打印info, debug, error
若指定级别为:debug, 可打印info ,debug
若指定级别: info, 可打印info
经分析,于是,得到初步思路:
由上图可知,每个子类都会有重复动作: 判断自己的level 是否小于给定的值,
于是在父类中再次进行集中实现( 并且, 把常量抽取到接口中,定义新的抽象方法 )得到下图:
具体代码如下:
定义:接口+父类=============================
public interface Write {
//常量
int info=1;
int warn=2;
int err=3;
//方法
void write();
}
/**
* 抽象父类: 集中(定义方法, 属性)
* @author wang
*
*/
public abstract class AbstractLogger implements Write {
//属性
int level;
AbstractLogger logger;
//构造
public AbstractLogger(int level) {
this.level = level;
}
public AbstractLogger(int level, AbstractLogger logger) {
this.level = level;
this.logger = logger;
}
//模板方法, 供外界调用
public void log(int level) {
//责任:日志打印
if(this.level<=level) {
this.write();
}
//责任链
if(logger!=null) {
logger.log(level);//传递任务
}
}
}
定义:子类=================================
public class ErrorLogger extends AbstractLogger{
//构造方法
public ErrorLogger(int level) {
super(level);
}
public ErrorLogger(int level, AbstractLogger logger) {
super(level, logger);
}
@Override
public void write() {
System.out.println("error #level......");
}
}
public class InfoLogger extends AbstractLogger {
//构造方法
public InfoLogger(int level) {
super(level);
}
public InfoLogger(int level, AbstractLogger logger) {
super(level, logger);
}
@Override
public void write() {
System.out.println("info #level......");
}
}
public class warnLogger extends AbstractLogger{
//构造方法
public warnLogger(int level) {
super(level);
}
public warnLogger(int level, AbstractLogger logger) {
super(level, logger);
}
@Override
public void write() {
System.out.println("warning #level......");
}
}
测试类===================================
public class Test {
public static void main(String[] args) {
//创建: 责任链条--->多个对象的链表
AbstractLogger foot = new ErrorLogger(Write.err);
AbstractLogger body = new InfoLogger( Write.info, foot);
AbstractLogger head = new warnLogger(Write.warn, body);
//调用方法
System.out.println("======err level=======");
head.log(AbstractLogger.err);
System.out.println();
System.out.println("======warn level=======");
head.log(AbstractLogger.warn);
System.out.println();
System.out.println("=====info level========");
head.log(AbstractLogger.info);
}
}
测试结果截图如下