22-04-18-책임연쇄패턴-2부-패턴적용하기
본문 바로가기
CS Study/디자인패턴

22-04-18-책임연쇄패턴-2부-패턴적용하기

by KyeongMin 2022. 4. 18.
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();
        }
    }
  • 요청처리, 응답처리할때 많이 쓰인다.

https://github.com/3DPIT/3dpit.github.io/blob/master/_posts/DesignPattern/22-04-18-%EC%B1%85%EC%9E%84%EC%97%B0%EC%87%84%ED%8C%A8%ED%84%B4-2%EB%B6%80-%ED%8C%A8%ED%84%B4%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0.md

 

728x90
반응형

댓글