


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(); } }
------以下是每一个处理者(包括后继者)都处理了, 顺序也是一级一级的传递------ 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment