명령 모드 - 디자인 모드 (1)

* command 명령 모드 는 대상 행위 형 모델 로 주로 해결 하 는 문 제 는 소프트웨어 구축 과정 에서 '행위 요구 자' 와 '행위 실현 자' 는 보통 '긴밀 한 결합' 문 제 를 나타 낸다.
* 때때로 우 리 는 특정한 대상 에 게 요청 을 해 야 하지만 요청 한 조작 이나 요청 을 받 은 수용자 에 대한 어떠한 정보 도 모 릅 니 다. 이때 변 화 를 막 을 수 없 는 긴밀 한 결합 은 적합 하지 않 습 니 다.예 를 들 어 행위 에 대해 '기록, 취소 / 재 작업, 사무' 등 처 리 를 해 야 한다.우리 가 해 야 할 일 은 의존 관 계 를 전환 시 키 고 긴밀 한 결합 을 느슨 한 결합 으로 바 꾸 는 것 이다.
위 키 피 디 아 위 키 백과 정의:
command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.
 
import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class CommandPattern {
    private int state;
    public CommandPattern(Integer state) {
        this.state = state;
    }
    public int addOne(Integer a){
        return state = state + a.intValue();
    }
    public int addTwo(Integer one,Integer two){
        return state = state + one.intValue() + two.intValue();
    }
 
    static class Command{
        private Object receiver;
        private Method action;
        private Object[] args;
  
        public Command(Object object,String methodName,Object[] args) {
            this.receiver = object;
            this.args = args;
            Class[] classTypes = new Class[args.length];
            for(int i=0;i<args.length;i++){
                classTypes[i] = args[i].getClass();
            }
            try {
                action = object.getClass().getMethod(methodName, classTypes);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            }
        }
  
        public Object execute(){
            try {
                 return action.invoke(receiver, args);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            return null;
         }
    }
 
    public static void main(String[] args) {
         System.out.println(new CommandPattern(0).addOne(3));
         System.out.println(new CommandPattern(0).addTwo(4,5));
         System.out.println("------------------------------------");
  
         Command command1 = new Command(new CommandPattern(0),"addOne",new Object[]{3});
         Command command2 = new Command(new CommandPattern(0),"addTwo",new Object[]{4,5});
         System.out.println(command1.execute());
         System.out.println(command2.execute());
    }
}

좋은 웹페이지 즐겨찾기