1.抽象处理器(Handler)
package com.vz.chain;
import java.util.Objects;
public abstract class Handler<Q,R> {
private Handler<Q,R> next;
private Handler<Q,R> last = this;
public final Handler<Q,R> add(Handler<Q,R> handler){
this.last.setNext(handler);
this.last = handler;
return this;
}
public final void setNext(Handler<Q,R> handler){
this.next = handler;
}
protected abstract R doHandle(Q request, R response);
public final R handle(Q request, R response){
response = this.doHandle(request, response);
if(Objects.nonNull(this.next)){
response = next.handle(request, response);
}
return response;
}
}
2.处理器实现类
package com.vz.chain;
public class AHandler extends Handler<XRequest, XResponse>{
@Override
protected XResponse doHandle(XRequest request, XResponse response) {
System.out.println("Handler A");
Long id = request.getId();
response.append(id);
response.addToTotal(id);
return response;
}
}
package com.vz.chain;
public class BHandler extends Handler<XRequest, XResponse>{
@Override
protected XResponse doHandle(XRequest request, XResponse response) {
System.out.println("Handler B");
Long id = request.getId() + 1;
response.append(id);
response.addToTotal(id);
return response;
}
}
package com.vz.chain;
public class CHandler extends Handler<XRequest, XResponse>{
@Override
protected XResponse doHandle(XRequest request, XResponse response) {
System.out.println("Handler C");
Long id = request.getId() + 2;
response.append(id);
response.addToTotal(id);
return response;
}
}
3.自定义参数和返回
package com.vz.chain;
import lombok.Data;
@Data
public class XRequest {
private Long id;
private String name;
}
package com.vz.chain;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class XResponse {
private Long total;
private List<Long> idList;
public void append(Long id){
if(idList == null){
idList = new ArrayList<>();
}
idList.add(id);
}
public void addToTotal(Long count){
if (total == null){
total = 0L;
}
total = total + count;
}
}
4.使用
package com.vz.chain;
import com.alibaba.fastjson.JSON;
public class Test {
public static void main(String[] args) {
XRequest request = new XRequest();
request.setId(1L);
request.setName("Hahaha");
XResponse response = new XResponse();
Handler<XRequest, XResponse> aHandler = new AHandler(), bHandler = new BHandler(), cHandler = new CHandler();
response = aHandler.add(bHandler).add(cHandler).handle(request, response);
System.out.println(JSON.toJSONString(response));
}
}
5.打印结果
Handler A
Handler B
Handler C
{"idList":[1,2,3],"total":6}