net.lulihu.designPattern.chain.ResponsibilityChain Maven / Gradle / Ivy
package net.lulihu.designPattern.chain;
/**
* 建议责任链的形式化实现
*
* 使用方式代码如下:
*
* public static class A extends ResponsibilityChain {
* public boolean support(AtomicInteger data) {
* return true;
* }
*
* public boolean resolve(AtomicInteger data) {
* System.out.println(data.intValue());
* data.incrementAndGet();
* return true;
* }
* }
*
* public static void main(String[] args) {
* ResponsibilityChain chain = new A();
* chain.addHandler(new A()).addHandler(new A());
* chain.handler(new AtomicInteger(1));
* }
*
*
* 注意:因为是以每个处理程序包含着下个处理程序的指针形成的责任模式,所有请使用第一个处理对象调用 handler方法
*/
public abstract class ResponsibilityChain extends AbstractHandlerResponsibilityChainResolver {
/**
* 持有下一个处理对象
*/
private ResponsibilityChain chain = null;
public ResponsibilityChain(String name) {
super(name);
}
/**
* 设置下个处理对象
*
* @param chain 下个处理对象
* @return 返回下个处理对象
*/
public ResponsibilityChain addHandler(ResponsibilityChain chain) {
this.chain = chain;
return chain;
}
/**
* 开始处理程序
*
* @param data 处理参数
*/
public void handler(T data) throws Exception {
try {
data = handlerEvent(data);
if (null != chain) chain.handler(data);
} catch (ChainDisconnectedException ignored) {
// 忽略
}
}
}