명령 모드 - 디자인 모드 (1)
* 때때로 우 리 는 특정한 대상 에 게 요청 을 해 야 하지만 요청 한 조작 이나 요청 을 받 은 수용자 에 대한 어떠한 정보 도 모 릅 니 다. 이때 변 화 를 막 을 수 없 는 긴밀 한 결합 은 적합 하지 않 습 니 다.예 를 들 어 행위 에 대해 '기록, 취소 / 재 작업, 사무' 등 처 리 를 해 야 한다.우리 가 해 야 할 일 은 의존 관 계 를 전환 시 키 고 긴밀 한 결합 을 느슨 한 결합 으로 바 꾸 는 것 이다.
위 키 피 디 아 위 키 백과 정의:
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());
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
디자인 모델 의 공장 모델, 단일 모델자바 는 23 가지 디자인 모델 (프로 그래 밍 사상/프로 그래 밍 방식) 이 있 습 니 다. 공장 모드 하나의 공장 류 를 만들어 같은 인 터 페 이 스 를 실현 한 일부 종 류 를 인 스 턴 스 로 만 드 는 것...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.