设置一个责任链抽象总承
public abstract class AbstractChain {
protected AbstractChain nextAbstractChain;
public AbstractChain setNextChain(AbstractChain abstractChain) {
this.nextAbstractChain = abstractChain;
return abstractChain;
}
public void next(Object obj) {
hander(obj);
if (Objects.nonNull(nextAbstractChain)) {
nextAbstractChain.next(obj);
}
}
public abstract void hander(Object obj);
}
编写实现类
public class LogHander extends AbstractChain {
@Override
public void hander(Object obj) {
System.out.println("责任链开始");
}
public static class Log1Hander extends AbstractChain {
@Override
public void hander(Object obj) {
System.out.println("1");
}
}
public static class Log2Hander extends AbstractChain {
@Override
public void hander(Object obj) {
System.out.println("2");
}
}
public static class Log3Hander extends AbstractChain {
@Override
public void hander(Object obj) {
System.out.println("3");
}
}
}
编写测试类
public class MainTest {
public static void main(String[] args) {
LogHander logHander = new LogHander();
LogHander.Log1Hander log1Hander = new LogHander.Log1Hander();
LogHander.Log2Hander log2Hander = new LogHander.Log2Hander();
LogHander.Log3Hander log3Hander = new LogHander.Log3Hander();
logHander.setNextChain(log1Hander).setNextChain(log2Hander).setNextChain(log3Hander);
logHander.next("obj");
}
}
结果