优雅的管理类的调用链路,符合开闭原则 添加与修改逻辑只需要修改调用链路即可。可以把类的执行顺序用链表或者list存储起来,存储的顺序就是类执行的顺序。
handler
public abstract class Handler<T> {
protected Handler next;
public void next(Handler next){ this.next = next;}
public abstract void doHandler(Member member);
public static class Builder<T>{
private Handler<T> head;
private Handler<T> tail;
public Builder<T> addHandler(Handler handler){
// do {
if (this.head == null) {
this.head = this.tail = handler;
return this;
}
this.tail.next(handler);
this.tail = handler;
// }while (false);//真正框架中,如果是双向链表,会判断是否已经到了尾部
return this;
}
public Handler<T> build(){
return this.head;
}
}
}
handler实现类
public class LoginHandler extends Handler {
public void doHandler(Member member) {
System.out.println("登录成功!");
member.setRoleName("管理员");
if(null != next) {
next.doHandler(member);
}
}
}
实用类
Handler.Builder builder = new Handler.Builder();
builder.addHandler(new LoginHandler());
// .addHandler(new LoginHandler())
// .addHandler(new AuthHandler());
builder.build().doHandler(new Member(loginName,loginPass));