[关闭]
@linux1s1s 2017-01-12T20:04:23.000000Z 字数 1992 阅读 1476

Base Time-Design Patterns-Chain of Responsibility

Base 2017-01


责任链模式的定义

责任链模式的优点

责任链模式的缺点

UML

此处输入图片的描述

Code

责任链处理节点接口ILogger.java

  1. public interface ILogger {
  2. int LEVEL_INFO = 1;
  3. int LEVEL_WARN = 2;
  4. int LEVEL_ERROR = 3;
  5. String TAG = "chainOfResponsibility";
  6. void setNextLogger(ILogger logger);
  7. void logMessage(int level, String message);
  8. void write(String message);
  9. }

基类,实现ILogger接口类BaseLogger.java

  1. public abstract class BaseLogger implements ILogger {
  2. private ILogger mNext;
  3. protected int mLevel;
  4. public BaseLogger() {
  5. mLevel = 0;
  6. }
  7. public BaseLogger(int level) {
  8. mLevel = level;
  9. }
  10. @Override
  11. public void setNextLogger(ILogger logger) {
  12. mNext = logger;
  13. }
  14. @Override
  15. public void logMessage(final int level, String message) {
  16. if (level <= mLevel) {
  17. write(message);
  18. }
  19. if (mNext != null) {
  20. mNext.logMessage(level, message);
  21. }
  22. }
  23. public abstract void write(String message);
  24. }

具体实现类InfoLogger.java

  1. public class InfoLogger extends BaseLogger {
  2. public InfoLogger() {
  3. super();
  4. mLevel = LEVEL_INFO;
  5. }
  6. @Override
  7. public void write(String message) {
  8. Log.i(TAG, "Info: " + message);
  9. }
  10. }

具体实现类WarnLogger.java

  1. public class WarnLogger extends BaseLogger {
  2. public WarnLogger() {
  3. super();
  4. mLevel = LEVEL_WARN;
  5. }
  6. @Override
  7. public void write(String message) {
  8. Log.w(TAG, "Warn: " + message);
  9. }
  10. }

具体实现类ErrorLogger.java

  1. public class ErrorLogger extends BaseLogger {
  2. public ErrorLogger() {
  3. super();
  4. mLevel = LEVEL_ERROR;
  5. }
  6. @Override
  7. public void write(String message) {
  8. Log.e(TAG, "Error: " + message);
  9. }
  10. }

测试用例类TestCase.java

  1. public class TestCase {
  2. private TestCase() {
  3. //Do Nothing
  4. }
  5. public static void exe() {
  6. //生成Logger链
  7. ILogger loggerInfo = new InfoLogger();
  8. ILogger loggerWarn = new WarnLogger();
  9. ILogger loggerError = new ErrorLogger();
  10. loggerInfo.setNextLogger(loggerWarn);
  11. loggerWarn.setNextLogger(loggerError);
  12. //放入责任链中执行
  13. loggerInfo.logMessage(ILogger.LEVEL_INFO, "LEVEL_INFO");
  14. loggerInfo.logMessage(ILogger.LEVEL_WARN, "LEVEL_WARN");
  15. loggerInfo.logMessage(ILogger.LEVEL_ERROR, "LEVEL_ERROR");
  16. }
  17. }

验证结果

此处输入图片的描述

参考博文:
Chain of Responsibility Pattern

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注