抽象Handler
package com.yimin.handler;
import com.yimin.dto.Ctx;
public abstract class AbsHandler {
private AbsHandler next;
public void execute(Ctx ctx) {
ctx = handle(ctx);
if (hasNext()) {
next.execute(ctx);
}
}
public abstract Ctx handle(Ctx ctx);
public void next(AbsHandler next) {
this.next = next;
}
public boolean hasNext() {
return next != null;
}
}
具体Handler
package com.yimin.handler;
import com.yimin.dto.Ctx;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Order(1)
@Component
public class FirstHandler extends AbsHandler {
@Override
public Ctx handle(Ctx ctx) {
System.out.println("first do");
// update ctx
return ctx;
}
}
package com.yimin.handler;
import com.yimin.dto.Ctx;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Order(2)
@Component
public class SecondHandler extends AbsHandler {
@Override
public Ctx handle(Ctx ctx) {
System.out.println("second do");
// update ctx
return ctx;
}
}
package com.yimin.handler;
import com.yimin.dto.Ctx;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Order(3)
@Component
public class ThirdHandler extends AbsHandler {
@Override
public Ctx handle(Ctx ctx) {
System.out.println("third do");
// update ctx
return ctx;
}
}
Ctx就是一个上下文对象,根据业务做相应修改
package com.yimin.dto;
public class Ctx {
}
Test
@SpringBootTest
class DemoApplicationTests {
@Autowired
private List<AbsHandler> chains;
@Test
void testOrderHandler() {
// 实际上不用排序,@Order已经决定了顺序
chains.sort(AnnotationAwareOrderComparator.INSTANCE);
for (int i = 0; i < chains.size(); i++) {
if (i == chains.size() - 1) {
chains.get(i).next(null);
} else {
chains.get(i).next(chains.get(i + 1));
}
}
chains.get(0).execute(new Ctx());
}
}
执行结果
first do
second do
third do