设计模式-------责任链模式
背景 : 登陆验证
1.基础验证类
/**
* Description : 基础的验证类
*/
abstract class Middleware {
// 责任链的下一个节点
Middleware next;
public Middleware(Middleware next) {
this.next = next;
}
public Middleware getNext() {
return next;
}
public void setNext(Middleware next) {
this.next = next;
}
abstract boolean precess(Request request);
}
2.子类验证类
1. 用户存在验证
public class UserExistMiddleware extends Middleware{
public UserExistMiddleware(Middleware next) {
super(next);
}
@Override
boolean precess(Request request) {
if (request.isUserExist()) {
if (getNext() == null) {
//没有下一个子链
return true;
}
// 调用下一个责任链的 precess
return getNext().precess(request);
}
return false;
}
}
2.敏感词汇验证
public class SensitiveWordMiddleware extends Middleware{
public SensitiveWordMiddleware(Middleware next) {
super(next);
}
@Override
boolean precess(Request request) {
if (!request.isContainSensitiveWords()) {
if (getNext() == null) {
//没有下一个子链
return true;
}
// 调用下一个责任链的 precess
return getNext().precess(request);
}
return false;
}
}
3.模拟请求验证
public class Request {
private boolean userExist;
private boolean userRoot;
private boolean containSensitiveWords;
public Request(boolean userExist, boolean userRoot, boolean containSensitiveWords) {
this.userExist = userExist;
this.userRoot = userRoot;
this.containSensitiveWords = containSensitiveWords;
}
//使用构建者创建对象
static class RequestBuilder {
private boolean userExist;
private boolean userRoot;
private boolean containSensitiveWords;
RequestBuilder userExist(User user) {
this.userExist = user.getName().equals("KD") && user.getPassword().equals("123");
return this;
}
RequestBuilder userRoot(User user) {
this.userRoot = user.getName().equals("CU");
return this;
}
RequestBuilder containSensitiveWords(User user) {
this.containSensitiveWords = user.getName().equals("FUCK");
return this;
}
public Request Builder() {
Request request = new Request(userExist, userRoot, containSensitiveWords);
return request;
}
}
public boolean isUserExist() {
return userExist;
}
public boolean isUserRoot() {
return userRoot;
}
public boolean isContainSensitiveWords() {
return containSensitiveWords;
}
}
3.测试
binding.firstButton.setOnClickListener {
val user = User(name = "KD", password = "123")
val request = Request.RequestBuilder().userExist(user).containSensitiveWords(user).Builder()
val userExistMiddleware = UserExistMiddleware(SensitiveWordMiddleware(null))
Log.e("youdianxiaoshuai","precess "+userExistMiddleware.precess(request))
}