제 프로그램에는 50 가지가 넘는 이벤트가 있습니다. 내가 겪고있는 문제는 이벤트를 수신하기위한 표준 방식으로 정착 중입니다.이벤트 톤, 코드 기반 축소 방법?
제 생각에는 제네릭 인터페이스를 사용하여 청취자에게이를 구현하고 수신기를 대기열에 추가하는 것뿐이었습니다. Unfortunately this meant that classes couldn't have multiple listeners due to type erasure and multiple inheritance issues. 그래서 리스너 코드를 제거하고 다시 시작했습니다.
내 현재 (및 원래) 설정은 각 이벤트를 수신하는 인터페이스를 갖는 것입니다.
/**
* Listener for {@link myproject.hooks.events.FingerEvent}events
* @see myproject.hooks.events.Finger
*/
public interface FingerListener extends Listener {
/**
* Invoked when an {@link myproject.hooks.events.FingerEvent}occurs
* @param event The generated FingerEvent
*/
public void onFinger(FingerEvent event);
}
예
그들은 모두 어떤 방법, 그 그들은 모두가 집단적으로 호출 할 수있는 단지 있도록 "청취자"를 포함하지 않는 인터페이스Listener
을 확장합니다.
문제는 이벤트 당 많은 코드가 있다는 것입니다. 당신은 이벤트와 그 getter를 가지고있다. (고맙게도 Project Lombok에 의해 간소화되었다.) 그리고 인터페이스를받는 인터페이스, 그리고 인터페이스상의 javadoc을 사용한다.
다른 문제는 각 수신기마다 다른 메서드 이름이있어서 호출 할 메서드를 찾는 매우 흥미로운 코드로 연결된다는 것입니다. 그 깨지기 쉬운, 천천히 (반사를 사용), 그리고 쓰레기처럼 보입니다. 당신이 다음 날, 믿지 않는 경우에 :
public static boolean callListener(Event event, Listener listener) {
//Get base name of event
String name = event.getClass().getSimpleName().split("Event")[0];
//Try and get the correct method if it exists
Method listenerMethod = null;
try {
listenerMethod = listener.getClass().getMethod("on"+name, event.getClass());
} catch (NoSuchMethodException ex) {
//Method doesn't exist, just don't call anything
return false;
} catch (SecurityException ex) {
throw new RuntimeException("Method on"+name+" is unaccessable", ex);
}
//Now that we have the method, attempt to execute it
try {
listenerMethod.invoke(listener, event);
} catch (Exception ex) {
throw new RuntimeException("Unexpected error when invoking method on"+name);
}
//Method executed sucessfully, return true
return true;
}
이 자바에서 이벤트를 수신 할 수있는 표준 방법하지만 : 다음 적절한 방법을 호출하는 스파게티를 만드는 각 이벤트에 대한 리스너 인터페이스를 가지고, 또는 내가이 일을하고있다 완전히 틀렸어?
재미있는 방법이 있습니다. MealListener는 내가 만드는 구체적인 클래스입니까? – TheLQ
MealListener는 생성 한 클래스입니다. 여러 청취자가 아침과 저녁에 대한 응답으로 다른 일을하기를 원한다면 추상적 일 수 있습니다. –
@Carl 사람이 여러 이벤트를 듣고 싶을 때 상황이 복잡해질 수 있습니다. 대부분이 작업을 수행했다면 이벤트와 단일 Listener 인터페이스를 제공하고 원하는 이벤트로 캐스트를 구현할 것입니다. – TheLQ