關於責任鏈模式的一個例子

zqs1031發表於2010-01-09
責任鏈模式就是現實中推責任的一種程式碼實現,這個用於校驗是不錯的選擇,有如下例子,主要完成對名稱、長度、大小的校驗:
首先定義一抽象類: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());

}
}

相關文章