Command Pattern

ayleen·2021년 12월 22일
0
post-thumbnail

- 요청을 객체(클래스파일)의 형태로 캡슐화함으로써(실행될 기능을 캡슐화) 주어진 여러 기능을 실행할 수 있는 재사용성이 높은 클래스를 설계하는 패턴

- 즉, 이벤트가 발생했을 때 실행될 기능이 다양하면서도 변경이 필요한 경우에 이벤트를 발생시키는 클래스를 변경하지 않고 재사용하고자 할 때 유용하다.

- 상속을 받고있지 않아서 메모리적으로 훨씬 효율적이다.




  1. 실행시킬 메소드 만들기
public void execute() {
	request.setCharacterEncoding("utf-8");
		
	String email = request.getParameter("email");
	String pw = request.getParameter("pw");
		
	memberDTO dto1 = new memberDTO(email, pw);
	memberDAO dao = new memberDAO();
	memberDTO dto = dao.Login(dto1);
		
	String nextpage = "";
	if(dto != null) {
			
		HttpSession session = request.getSession();
		session.setAttribute("dto", dto);
		response.sendRedirect("main.jsp");
			
	}else {
		response.sendRedirect("LoginFalse.jsp");
			
	}		
}

메소드 안에는 컨트롤러 안에 있던 코드들을 모두 잘라와서 붙여준다.
→ request와 response부분에서 다 오류남.
일반 자바 클래스 파일은 request/response가 없어서.



  1. 원래 있던 컨트롤러 if문 안에 아래 코드 넣어준다.
LoginService login = new LoginService();
login.execute(request, response);

servlet이 가지고 있는 request/response를 class에 빌려주기.



  1. 클래스파일에서 request/ response 받아주기
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	...
}

메소드 괄호 안에서 request와 response를 받아준다.
이 때, request/response 부분에서 런타임 오류 발생
→ 메서드 괄호 뒷쪽에 throws ServletException, IOException 붙여주기
→ throws : 예외처리
try-catch : try 안쪽 부분만 예외처리됨(그 밖에 있는 다른 부분은 예외처리 안됨).
throws : 메소드 안에 있는 전체 코드에 예외처리가 걸림(예외처리가 필요하지 않은 부분까지 예외처리가 됨). 사용하기에는 편하지만 메모리적으로는 훨씬 비효율적이다.
** throws를 사용하고싶지 않다면 하나하나의 코드에 try-catch문을 걸어주면 된다.



  1. interface를 만들어준다.
public interface Command {

	public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
		
}

설계도라고도 한다.
여러 사람이 같이 만들면 메서드 이름, 변수 이름, 파일 이름 등이 다 달라져버린다. 여러명의 개발자가 동시에 개발을 할 때 하나의 정해진 규칙을 가지고 개발을 할 수 있다.
** interface는 기능을 정의하는 구역이 아닌 그냥 규칙이다. 중괄호 필요 없음!



  1. 클래스파일에 impeliements 해주기.
public class LoginService implements Command{
	...
}



  1. upcasting
Command com = null;
String nextpage = null;

if(command.equals("LoginCon.do")) {
	com = new LoginService();
	nextpage = com.execute(request, response);
}

부모의 이름으로 자식을 형변환하기
컨트롤러의 if문 안을 upcasting으로 바꿔준다.
모든 클래스들이 implements Command를 하고 있으니까 Command com = null;로 전역변수 설정해주고 com = new LoginService();로 자식을 생성하면서 부모로 형변환 시켜준다.
** 여러개의 객체 생성이 가능하다.

profile
asdf

3개의 댓글

comment-user-thumbnail
2021년 12월 22일

impeliements 에 대한 설명 좀 더 부탁드립니다~

1개의 답글
comment-user-thumbnail
2021년 12월 23일

만들어준 설계도인 interface를 상속받아주기 위해 사용합니다!

-> 더 친절하고 쉬운 설명으로 한번 부탁드리겠습니다:)

답글 달기