2011년 2월 1일 화요일

간단한 디자인패턴-Command패턴

음.. 한 6년전에 정리하면서 만든 자료지만..
정리차 올립니다.

Command 패턴
Command 패턴은 인터페이스를 이용해서 내부에서 실행되는 객체가 무언지 모르는 상태에서
동일한 과정으로 메쏘드를 수행하고 싶을 때 사용하는 패턴이다.



다음과 같은 경우를 생각해 보자.
. Escm에서 여러개의 매니저가 존재한다.

. 각 매니저는 자신이 수행하기에 적합한 메쏘드가 있다.
. 매니저에게 동작을 시키고자 할 때 통일성을 갖게 하고자 하고 싶다.
예를 들어 파라미터의 값에 따라 자동적으로 특정 객체를 찾아내는 로직을 분리하고
특정 객체의 메쏘드는 인터페이스를 구현하도록 하면 다음과 같은 장점이 생길 수 있다.
. 어떤 객체이건간에 동일한 메쏘드 호출하면 된다.
. 새로운 객체를 추가할 때에도 인터페이스에 맞게 구현해 주면 된다.
이를 위해서 개발자가 먼저 해야 하는 것은 단 하나이다.

****인터페이스에서 코딩을 시작하라 *****
-----------------------------------------------------
Processable
-----------------------------------------------------
package command;
public interface Processable {

 public Object process()throws Exception;
}
-----------------------------------------------------
DocManager
-----------------------------------------------------
package command;
public class DocManager implements Processable {
 public Object process() throws Exception {
  System.out.println("DocManager의 처리 ");

  return null;
 }
}
-----------------------------------------------------
PodManager
-----------------------------------------------------
package command;
public class PodManager implements Processable {
 public Object process() throws Exception {
  System.out.println("PodManager의 처리 ");
  return null;
 }
}

-----------------------------------------------------
CommandTest
-----------------------------------------------------
package command;
public class CommandTest {

 Processable process = null;
 public static void main(String[] args) {

  CommandTest ct = new CommandTest();
  if(args.length < 1){
   System.out.println("args is null");
   return;
  }
  ct.test(args[0]);
 }
 private void test(String param) {

  Executor executor = new Executor();

  if(param.equals("1") == true ){
   process = new DocManager();
  }else{
   process = new PodManager();
  }

  executor.doJob(process);
 }
}
-----------------------------------------------------
Executor
-----------------------------------------------------
package command;
public class Executor {
 Processable command = null;

 public void doJob(Processable command){
  this.command = command;

  try{
   Object result = command.process();
 
  }catch(Exception e){
   e.printStackTrace();
  }
 }
}
디자인 패턴의 원칙이 '구현이 아니라 구성이다'이라는 원칙대로 인터페이스를 설계하고
인터페이스에 따라서 동작이 가능하게 하는 방식이다.
일반적인 경우에 Command패턴과 Strategy Pattern을 적용해서 많이 사용한다.

댓글 없음:

댓글 쓰기