728x90
반응형
01.책임연쇄패턴 적용하기
01.1 RequestHandler
- before
-
public class RequestHandler{ public handler(Request request){ System.out.println(request.getBody()); } }
- after
-
public abstract class RequestHandler{ private RequestHandler nextHandler; public RequestHandler(RequestHandler nextHandler){ this.nextHandler = nextHandler; } public void handle(Request request){ if(nextHandler != null){ nextHandler.handle(request); } } }
01.2 PrintRequestHandler
public class PrintRequestHandler extends RequestHandler{
private PrintRequestHandler nextHandler;
public PrintRequestHandler(RequestHandler nextHandler){
super(nextHandler);
}
@Override
public void handle(Request request){
System.out.println(request.getBody());
super.handle(request);
}
}
01.3 AuthRequestHandler
public class AuthRequestHandler extends RequestHandler{
public AuthRequestHandler(RequestHandler nextHandler){super(nextHandler);}
@Override
public void handle(Request request){
System.out.println("인증이 되었는가?");
super.handle(request);
}
}
01.4 LoggingRequestHandler
public class LoggingRequestHandler extends RequestHandler{
public LoggingRequestHandler(RequestHandler nextHandler){super(nextHandler);}
@Override
public void handle(Request request){
System.out.println("로깅이 되었는가?");
super.handle(request);
}
}
01.5 Client
- before
-
public class Client{ public static void main(String[] args){ Request request = new Request("무궁화 꽃이 피었습니다."); RequestHandler requestHandler = new RequestHandler(); requestHander.handler(request); } }
- after
- 가장 중요한것은 이렇게 함으로써 클라이언트가 구체적인 핸들러타입을 결정안해도됨
- 요청을 처리하는 쪽과 디커플되어있음, 타이트하게 묶여있지 않음
- 가장 중요한것은 이렇게 함으로써 클라이언트가 구체적인 핸들러타입을 결정안해도됨
-
public class Client{ private RequestHandler requestHandler; public Client(RequestHandler requestHandler){ this.requestHandler = requestHandler; } public void doWork(){ Request request = new Request("이번 놀이는 뽑기 입니다."); requestHandler.handle(request); } public static void main(String[] args){ RequestHandler chain = new AuthRequestHandler(new LoggingRequestHandler(new PrintRequestHandler(null))); Client client = new Client(chain); client.doWork(); } }
- 요청처리, 응답처리할때 많이 쓰인다.
728x90
반응형
'CS Study > 디자인패턴' 카테고리의 다른 글
22-04-18-책임연쇄패턴-4부-장점과단점 (0) | 2022.04.18 |
---|---|
22-04-18-책임연쇄패턴-3부-장점과단점 (0) | 2022.04.18 |
22-04-17-책임연쇄패턴-1부-패턴소개 (0) | 2022.04.18 |
22-04-17-프록시패턴-4부-자바와스프링에서찾아보는패턴 (0) | 2022.04.17 |
22-04-17-프록시패턴-3부-장점과단점 (0) | 2022.04.17 |
댓글