Web programming/Patterns
Command Design Pattern
row_a_boat
2021. 4. 18. 17:37
Command Design Pattern :
- 요구사항(예-컨트롤러로직)을 객체로 캡슐화하여 처리
- 명령을 쉽게하기 위한 목적
- 사장님(수신자or 사용자) 측은 표준화된 단일한 메세지 방식으로 다양한 요구사항(예-컨트롤러로직)을 실행할 수 있
- 대표적인 Command pattern - > Thread의 Runnable interface와 구현체
ex)
*
* FrontControllerServlet --execute() ----> FindController 의 검색작업이 실행
* ------> RegisterController의 등록작업이 실행
*
* public interface Runnable{
* public void run(){}
* }
//testcommandpattern.java
class VideoWorker implements Runnable{
public void run() {
System.out.println("비디오 실행");
}
}
class AudioWorker implements Runnable{
public void run() {
System.out.println("오디오 실행");
}
}
public class TestCommandPattern {
public static void main(String[] args) {
Thread t1= new Thread(new VideoWorker());
t1.start();
Thread t2= new Thread(new AudioWorker());
t2.start();
}
}
test1은 Thread의 Runnable interface와 구현체로 이와 밑의 command patternd을 비교해 보자.
//testcommandpattern2.java
interface Controller{
public void execute();
}
//abstract 메서드를 생성
class FindCarController implements Controller{
@Override
public void execute() {
System.out.println("차정보 검색작업");
}
}
class RegisterController implements Controller{
@Override
public void execute() {
System.out.println("차정보 등록작업");
}
}
public class TestCommandPattern2 {
public static void main(String[] args) {
Controller c = new FindCarController();
c.execute();
Controller c2= new RegisterController();
c2.execute();
//execute()만 호출하면 된다
//100개든 200개든 execute()로 실행이 가능해짐. -> 사장님은 간단하게 사용가능
}
Thread하나와 Controller하나가 자리만 바뀐거 같은 느낌이든다. 사장님은 메인에서 execute만 해주면 pattern이 알아서
차정보 검색작업인지 등록작업인지 판단해서 척척해주니 사장님은 오늘 조금 행복해졌다.