模拟登录校验
先创建一个 Handler 的抽象类,这个类里面有一个下一个 Handler 处理器 next,还有一个 Builder,这个就是用来构建链的,也是方便我们的链式编程。
public abstract class Handler<T> {
protected Handler next;
private 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) {
if (this.head == null) {
this.head = this.tail = handler;
return this;
}
this.tail.next(handler);
this.tail = handler;
return this;
}
public Handler<T> build() {
return this.head;
}
}
}
下面写非空校验 ValidateHandler 类,这里面先判断用户名和密码是否为空,空的话返回,非空的话判断 next 是否为空,非空的话就丢给下一个处理器去执行。
public class ValidateHandler extends Handler {
@Override
public void doHandler(Member member) {
if (StringUtils.isEmpty(member.getUsername()) ||
StringUtils.isEmpty(member.getPassword())) {
System.out.println("用户名和密码不能为空");
return;
}
if (null != next) {
next.doHandler(member);
}
}
}
创建登录检验LoginHandler类,判断账号密码是否正确
public class LoginHandler extends Handler {
@Override
public void doHandler(Member member) {
if (!"jack".equals(member.getUsername()) || !"666".equals(member.getPassword())) {
System.out.println("用户名密码不正确");
return;
}
if (null != next) {
next.doHandler(member);
}
}
}
创建权限检验 AuthHandler 类,判断角色是否有权限
public class AuthHandler extends Handler {
@Override
public void doHandler(Member member) {
if (!"管理员".equals(member.getRoleName())) {
System.out.println("您不是管理员,没有操作权限");
return;
}
if (null != next) {
next.doHandler(member);
}
}
}
创建执行业务逻辑类
public class BusinessLogicHandler extends Handler {
@Override
public void doHandler(Member member) {
System.out.println("执行业务逻辑。。");
}
}
public class Test {
public static void main(String[] args) {
Handler.Builder builder = new Handler.Builder();
//这里就是链式编程,谁在前谁在后看的清清楚楚,明明白白
builder.addHandler(new ValidateHandler())
.addHandler(new LoginHandler())
.addHandler(new AuthHandler())
.addHandler(new BusinessLogicHandler());
Member member = new Member();
member.setUsername("");
member.setPassword("");
builder.build().doHandler(member);
}
}