栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

设计模式-责任链模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

设计模式-责任链模式

责任链模式
  • 抽象处理者
    • AbstractLog
  • 具体处理者
    • DebugLog
    • InfoLog
    • ErrorLog
  • 测试


责任链模式属于行为型模式

责任链模式中,处理者持有对下家的引用,
形成一条链,请求在这个链上传递,直到某一个处理者处理此请求,
或者不处理一直到责任链结束。

责任链可能是一条线,也可能是一条环链。

包含有抽象处理者、具体处理者两种角色。

我们以不同级别的日志打印为例

抽象处理者 AbstractLog
package com.example.duohoob.dp.responsibilitychain;


public abstract class AbstractLog {

	
	protected int level;
	
	
	protected AbstractLog nextLog;

	public void setNextLog(AbstractLog nextLog) {
		this.nextLog = nextLog;
	}
	
	
	public abstract void logMessage(String message);
	
	
	public void handlerRequest(int level, String message) {
		if (!(level > this.level)) {
			// 可以处理,不大于当前日志级别
			logMessage(message);
		} else {
			// 不能处理,看是否有下一处理者
			if (null != nextLog) {
				nextLog.handlerRequest(level, message);
			}
		}
	}
	
}
具体处理者 DebugLog
package com.example.duohoob.dp.responsibilitychain;


public class DebugLog extends AbstractLog {

	public DebugLog() {
		level = 1;
	}
	
	@Override
	public void logMessage(String message) {
		// TODO Auto-generated method stub
		System.out.println("DebugLog打印***" + message);
	}

}

InfoLog
package com.example.duohoob.dp.responsibilitychain;


public class InfoLog extends AbstractLog {

	public InfoLog() {
		level = 2;
	}

	@Override
	public void logMessage(String message) {
		// TODO Auto-generated method stub
		System.out.println("InfoLog打印***" + message);
	}

}

ErrorLog
package com.example.duohoob.dp.responsibilitychain;


public class ErrorLog extends AbstractLog {

	public ErrorLog() {
		level = 3;
	}
	
	@Override
	public void logMessage(String message) {
		// TODO Auto-generated method stub
		System.out.println("ErrorLog打印***" + message);
	}

}

测试
package com.example.duohoob.dp.responsibilitychain;


public class LogTest {

	
	public static AbstractLog getChain() {
		AbstractLog debugLog = new DebugLog();
		
		AbstractLog infoLog = new InfoLog();
		debugLog.setNextLog(infoLog);
		
		AbstractLog errorLog = new ErrorLog();
		infoLog.setNextLog(errorLog);
		
		return debugLog;
	}
	
	public static void main(String[] args) {
		AbstractLog abstractLog = getChain();
		abstractLog.handlerRequest(1, "debug级别的日志");
		abstractLog.handlerRequest(2, "info级别的日志");
		abstractLog.handlerRequest(3, "error级别的日志");
	}
	
}

运行

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1013975.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号