定义
责任链模式为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。
避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| public abstract class AbstractLogger{ public static int INFO = 1; public static int DEBUG = 2; public static int ERROR = 3;
protected int level;
protected AbstractLogger nextLogger;
public void setNextLogger(AbstractLogger logger){ this.nextLogger = logger; }
public void log(int level, String msg){ if(this.level <= level){ write(msg); } if(nextLogger != null){ nextLogger.log(level, msg); } }
abstract protected void write(String msg); }
public class ConsoleLogger extends AbstractLogger{ public ConsoleLogger(int level){ this.level = level; }
@Override protected void write(String msg){ System.out.println(""+msg); } }
public class ErrorLogger extends AbstractLogger{ public ErrorLogger(int level){ this.level = level; }
@Override protected void write(String msg){ System.out.println(""+msg); } }
public class FileLogger extends AbstractLogger{ public FileLogger(int level){ this.level = level; }
@Override protected void write(String msg){ System.out.println(""+msg); } }
public class Demo{ public static void main(String[] args){ ConsoleLogger logger1 = new ConsoleLogger(AbstractLogger.INFO); FileLogger logger2 = new FileLogger(AbstractLogger.DEBUG); ErrorLogger logger3 = new ErrorLogger(AbstractLogger.ERROR); logger2.setNextLogger(logger1); logger3.setNextLogger(logger2); logger3.log(AbstractLogger.INFO,"这是info级别的日志"); logger3.log(AbstractLogger.DEBUG,"这是debug级别的日志"); logger3.log(AbstractLogger.ERROR,"这是error级别的日志"); } }
|
优点
1、降低耦合度,请求的发送者和接收者解耦
2、简化对象,对象不需要知道链的结构
3、增强灵活性,可以改变顺序,增删成员改变链内对象的顺序或存在
4、增加新的处理方式很容易
缺点
1、不能保证请求一定能被处理(或许必须要做一个兜底处理者)
2、链式调用,性能会有影响
3、不容易观察运行时的特征