使用责任链模式将以往的代码进行了重构,应用场景是这样的:
请求第三方接口,获取数据,然后走a步骤处理,提交至a1处,之后走b步骤处理提交至b1处,走c步骤处理提交至c1处;
原有的流程是,在a处结束后调用b,b处结束后调用c,这样做的弊端是流程不清晰,调试排错的时候得debug--步步跟踪,不利于后续代码维护和扩
调整后的流程:
各个步骤声明为责任链的链接点,
在初始化调用处,将各个链接点链接起来,如
a->b->c,数据由a入口今日责任链内部流转,并在c处返回最终结果,这样做的好处是屏蔽底层细节,并且流程节点清晰,易于后续维护扩展,比如我需要在中间加个节点,只需新增相应代码,并在调用.处声明并加入责任链,再比如说,一个新需求只需要b->C,或者b->a,我只需要调整责任链的节点位置即可.
代码如下:
==========================================================
public abstract class ChainNode {
private ChainNode next;
public abstract <T>T doPost(Object object);
public ChainNode() {
super();
}
public ChainNode next() {
return next;
}
public ChainNode appendNext(ChainNode next) {
this.next = next;
return this;
}
}
==========================================================
public class Chain1 extends ChainNode{
@Override
public <T> T doPost(Object object) {
System.out.printf("Chain3");
ChainNode next = super.next();
if (null == next) {
return null;
}
return next.doPost(object);
}
}
==========================================================
public class Chain2 extends ChainNode{
@Override
public <T> T doPost(Object object) {
System.out.printf("Chain2");
ChainNode next = super.next();
if (null == next) {
return null;
}
return next.doPost(object);
}
}
==========================================================
public class Chain3 extends ChainNode{
@Override
public <T> T doPost(Object object) {
System.out.printf("Chain3");
ChainNode next = super.next();
if (null == next) {
return null;
}
return next.doPost(object);
}
}
==========================================================
public class ChainTest {
public static void testChain(){
ChainNode chainNode=new Chain1().appendNext(new Chain2().appendNext(new Chain3()));
chainNode.doPost(new Object());
}
public static void main(String[] args) {
ChainTest.testChain();
}
}
媛代码社区微信公众号