Home  >  Article  >  Java  >  Detailed explanation of how Java implements the Chain of Responsibility model with clear responsibilities

Detailed explanation of how Java implements the Chain of Responsibility model with clear responsibilities

黄舟
黄舟Original
2017-03-11 11:19:281805browse

Class diagram


/**
 * 抽象责任
 * @author stone
 *
 */
public abstract class IFilter {
	private IFilter successor;

	public IFilter getSuccessor() {
		return successor;
	}

	public void setSuccessor(IFilter successor) {
		this.successor = successor;
	}
	
	public abstract void handleFilter();
	
	public abstract void handleFilter2();
}
/**
 * 具体责任
 * @author stone
 *
 */
public class ConcreteFilter extends IFilter {
	
	private String name;
	public ConcreteFilter(String name) {
		this.name = name;
	}
	
	@Override
	public void handleFilter() {
		/*
		 * 自己先处理,如有后继者,再由它处理一次
		 */
		System.out.println(name + " 处理了请求");
		if (getSuccessor() != null) {
			getSuccessor().handleFilter();
		}
	}
	
	@Override
	public void handleFilter2() {
		/*
		 * 有后继者就后继者处理, 否则自己处理
		 */
		if (getSuccessor() != null) {
			getSuccessor().handleFilter2();
		} else {
			System.out.println(name + " 处理了请求");
		}
	}
}
/*
 * 责任链(Chain of Responsibility)模式		行为型模式
 * 将责任一级一级传递给后继者,直至某一个后继者处理了
 * 行为表现在:责任的传递,需要是一个链一个
 */
public class Test {
	public static void main(String[] args) {
		IFilter filter1 = new ConcreteFilter("permission-filter");//权限过滤
		IFilter filter2 = new ConcreteFilter("suffix-filter");//后缀名过滤
		IFilter filter3 = new ConcreteFilter("style-filter");//风格过滤
		filter1.setSuccessor(filter2);
		filter2.setSuccessor(filter3);
		System.out.println("------以下是每一个处理者(包括后继者)都处理了, 顺序也是一级一级的传递------");
		filter1.handleFilter();
		
		System.out.println("------以下是交由最后一个后继者处理------");
		filter1.handleFilter2();
		
	}
}

Print

------以下是每一个处理者(包括后继者)都处理了, 顺序也是一级一级的传递------
permission-filter 处理了请求
suffix-filter 处理了请求
style-filter 处理了请求
------以下是交由最后一个后继者处理------
style-filter 处理了请求

The above is the detailed content of Detailed explanation of how Java implements the Chain of Responsibility model with clear responsibilities. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn