@linux1s1s
2017-01-12T20:04:23.000000Z
字数 1992
阅读 1469
Base
2017-01
责任链处理节点接口ILogger.java
public interface ILogger {
int LEVEL_INFO = 1;
int LEVEL_WARN = 2;
int LEVEL_ERROR = 3;
String TAG = "chainOfResponsibility";
void setNextLogger(ILogger logger);
void logMessage(int level, String message);
void write(String message);
}
基类,实现ILogger接口类BaseLogger.java
public abstract class BaseLogger implements ILogger {
private ILogger mNext;
protected int mLevel;
public BaseLogger() {
mLevel = 0;
}
public BaseLogger(int level) {
mLevel = level;
}
@Override
public void setNextLogger(ILogger logger) {
mNext = logger;
}
@Override
public void logMessage(final int level, String message) {
if (level <= mLevel) {
write(message);
}
if (mNext != null) {
mNext.logMessage(level, message);
}
}
public abstract void write(String message);
}
具体实现类InfoLogger.java
public class InfoLogger extends BaseLogger {
public InfoLogger() {
super();
mLevel = LEVEL_INFO;
}
@Override
public void write(String message) {
Log.i(TAG, "Info: " + message);
}
}
具体实现类WarnLogger.java
public class WarnLogger extends BaseLogger {
public WarnLogger() {
super();
mLevel = LEVEL_WARN;
}
@Override
public void write(String message) {
Log.w(TAG, "Warn: " + message);
}
}
具体实现类ErrorLogger.java
public class ErrorLogger extends BaseLogger {
public ErrorLogger() {
super();
mLevel = LEVEL_ERROR;
}
@Override
public void write(String message) {
Log.e(TAG, "Error: " + message);
}
}
测试用例类TestCase.java
public class TestCase {
private TestCase() {
//Do Nothing
}
public static void exe() {
//生成Logger链
ILogger loggerInfo = new InfoLogger();
ILogger loggerWarn = new WarnLogger();
ILogger loggerError = new ErrorLogger();
loggerInfo.setNextLogger(loggerWarn);
loggerWarn.setNextLogger(loggerError);
//放入责任链中执行
loggerInfo.logMessage(ILogger.LEVEL_INFO, "LEVEL_INFO");
loggerInfo.logMessage(ILogger.LEVEL_WARN, "LEVEL_WARN");
loggerInfo.logMessage(ILogger.LEVEL_ERROR, "LEVEL_ERROR");
}
}