关于责任链模式的一个例子

10-01-09 zqs1031
         

责任链模式就是现实中推责任的一种代码实现,这个用于校验是不错的选择,有如下例子,主要完成对名称、长度、大小的校验:

首先定义一抽象类:BaseChecker

public abstract class BaseChecker {

private BaseChecker checker;

protected CheckResult genSuccessResult() {

return new CheckResult(true, "000000", "");

}

protected CheckResult genFailResult(String errorCode, String errorMsg) {

return new CheckResult(false, errorCode, errorMsg);

}

public CheckResult doCheck() {

CheckResult result = check();

if (result.isPass()) {

return checker == null ? genSuccessResult() : checker.doCheck();

}

return result;

}

protected abstract CheckResult check();

public BaseChecker getChecker() {

return checker;

}

public void setChecker(BaseChecker checker) {

this.checker = checker;

}

}

以下是几个校验类:

public class FacadeChecker extends BaseChecker {

@Override

protected CheckResult check() {

setChecker(new NameChecker());

return genSuccessResult();

}

}

public class NameChecker extends BaseChecker {

public CheckResult check() {

System.err.println("名称校验");

setChecker(new LengthChecker());

return genSuccessResult();

}

}

public class LengthChecker extends BaseChecker {

@Override

public CheckResult check() {

System.err.println("长度校验");

setChecker(new SizeChecker());

return genSuccessResult();

}

}

public class SizeChecker extends BaseChecker {

@Override

public CheckResult check() {

System.err.println("大小校验");

setChecker(new DefaultChecker());

return genSuccessResult();

}

}

public class DefaultChecker extends BaseChecker {

@Override

public CheckResult check() {

System.err.println("校验通过");

return genSuccessResult();

}

}

public class CheckResult {

private boolean isPass;

private String code;

private String message;

public CheckResult(boolean isPass, String code, String message) {

this.isPass = isPass;

this.code = code;

this.message = message;

}

public boolean isPass() {

return isPass;

}

public void setPass(boolean isPass) {

this.isPass = isPass;

}

public String getCode() {

return code;

}

public void setCode(String code) {

this.code = code;

}

public String getMessage() {

return message;

}

public void setMessage(String message) {

this.message = message;

}

}

调用如下所示:

public class Client {

public static void main(String[] args) {

BaseChecker checker = new FacadeChecker();

System.err.println(checker.doCheck().getMessage());

}

}

         

4
banq
2010-01-09 19:52

不错。