您的位置:首页 > 大数据 > 人工智能

Chain of Responsibility 责任链模式

2009-12-02 08:58 459 查看
模式定义
责任链模式是一种对象的行为模式。在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求,这使得系统可以在不影响客户端的情况下动态地重新组织链和分配责任。责任链模式要求某个处理对象要么直接处理,要么转到下一个链处理,不允许处理一半再移交一半。 Windows操作系统的消息处理机制十分类似这种模式。



使用方法
一个责任链上多个处理类各自包含了下一个处理类的对象,当当前的处理对象无法处理时,必须马上移交给下一个链上的处理对象。





使用范围

多个处理类可以处理一个请求。

客户类无须知道请求究竟被谁处理了。


举例说明
假设有个Logger用来记录应用程序的日志,记录普通的INFORMATION时,只在标准输出界面上显示该INFORMATION;当记录DEBUG的信息时候,将信息记录到文件;当记录ERROR信息的时候,则把信息发送到email。
abstract class Logger{
    public static int ERROR = 0;
    public static int DEBUG = 1;
    public static int INFORMATION = 2;

    protected int mask;

    // The next element in the chain of responsibility
    protected Logger next;
    public Logger setNext( Logger log)
    {
        next = log;
        return log;
    }

    abstract protected void writeMessage( int priority, String msg );

}


setNext()方法用来保存当前Logger链上的下一个处理对象。
以下是不同的处理类各自实现自己的处理方法,当发现无法处理请求时,马上交给链上的处理类:next.writeMessage(..)。
public class StandoutLogger extends Logger{

	protected void writeMessage(int priority, String msg) {
		if (priority == Logger.INFORMATION){
			System.out.println("Standout:" + msg);
		}else if (next!=null){ 
			next.writeMessage(priority, msg);
		}
	}
}
----------
public class FileLogger extends Logger{

	protected void writeMessage(int priority, String msg) {
		if (priority == Logger.DEBUG){
			System.out.println("File:" + msg);
		}else if (next!=null){
			next.writeMessage(priority, msg);
		}

	}
};
---------
public class EmailLogger extends Logger{

	protected void writeMessage(int priority, String msg) {
		if (priority == Logger.ERROR){
			System.out.println("Email:" + msg);
		}else if (next!=null){
			next.writeMessage(priority, msg);
		}
	}
}


再观察客户类,它无需知道究竟谁处理了该请求,它只关心有没有被处理。
public class Client {
	public static void main(String args[]){
		StandoutLogger log = new StandoutLogger();
		FileLogger flog = new FileLogger();
		EmailLogger elog = new EmailLogger();

		log.setNext(flog);
		flog.setNext(elog);

		log.writeMessage(Logger.DEBUG, "debug information");
	}
}




下载示例

Java代码 zigzagsoft_designpattern_chain.zip
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: