April 18, 2022
01.책임연쇄패턴 적용하기
01.1 RequestHandler
01.2 PrintRequestHandler
01.3 AuthRequestHandler
01.4 LoggingRequestHandler
01.5 Client
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);
}
}
}
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);
}
}
public class AuthRequestHandler extends RequestHandler{
public AuthRequestHandler(RequestHandler nextHandler){super(nextHandler);}
@Override
public void handle(Request request){
System.out.println("인증이 되었는가?");
super.handle(request);
}
}
public class LoggingRequestHandler extends RequestHandler{
public LoggingRequestHandler(RequestHandler nextHandler){super(nextHandler);}
@Override
public void handle(Request request){
System.out.println("로깅이 되었는가?");
super.handle(request);
}
}
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();
}
}