责任链模式:
一个请求的处理需要多个对象当中的一个或几个协作处理。
/** * 责任链模式 */ public class responsibility { public static void main(String[] args) { // Request request = new Request.RequestBuilder().frequentOk(true).loggedOn(true).build(); Request request = new Request.RequestBuilder().frequentOk(true).loggedOn(false).build(); RequestFrequenthandler requestFrequenthandler = new RequestFrequenthandler(new Logininghandler(null)); if (requestFrequenthandler.process(request)){ System.out.println("正常业务处理。。。"); }else { System.out.println("访问异常。。。"); } } } class Request{ private boolean loggedOn; private boolean frequentOk; private boolean isPermits; private boolean containsSensitiveWords; private boolean requestBody; public Request(boolean loggedOn, boolean frequentOk, boolean isPermits, boolean containsSensitiveWords) { this.loggedOn = loggedOn; this.frequentOk = frequentOk; this.isPermits = isPermits; this.containsSensitiveWords = containsSensitiveWords; } public boolean isLoggedOn(){ return loggedOn; } public boolean isfrequentOk(){ return frequentOk; } public boolean isPermits(){ return isPermits; } public boolean iscontainsSensitiveWords(){ return containsSensitiveWords; } static class RequestBuilder{ private boolean loggedOn; private boolean frequentOk; private boolean isPermits; private boolean containsSensitiveWords; RequestBuilder loggedOn(boolean loggedOn){ this.loggedOn = loggedOn; return this; } RequestBuilder frequentOk(boolean frequentOk){ this.frequentOk = frequentOk; return this; } RequestBuilder isPermits(boolean isPermits){ this.isPermits = isPermits; return this; } RequestBuilder containsSensitiveWords(boolean containsSensitiveWords){ this.containsSensitiveWords = containsSensitiveWords; return this; } public Request build() { Request request = new Request(loggedOn, frequentOk, isPermits, containsSensitiveWords); return request; } } } abstract class Handler{ Handler next; public Handler getNext() { return next; } public void setNext(Handler next) { this.next = next; } public Handler(Handler next) { this.next = next; } abstract boolean process(Request request); } class RequestFrequenthandler extends Handler{ public RequestFrequenthandler(Handler next) { super(next); } @Override boolean process(Request request) { System.out.println("访问频率控制。。。"); if (request.isfrequentOk()){ Handler next = getNext(); if (null == next){ return true; } if (next.process(request)){ return true; }else { return false; } } return false; } } class Logininghandler extends Handler{ public Logininghandler(Handler next) { super(next); } @Override boolean process(Request request) { System.out.println("登录验证。。。"); if (request.isLoggedOn()){ Handler next = getNext(); if (null == next){ return true; } if (next.process(request)){ return true; }else { return false; } } return false; } }