在Java中,注冊事件監聽器通常涉及以下幾個步驟:
MyListener
的接口:public interface MyListener {
void onEventOccurred(String message);
}
EventPublisher
的類:import java.util.ArrayList;
import java.util.List;
public class EventPublisher {
private List<MyListener> listeners = new ArrayList<>();
public void addListener(MyListener listener) {
listeners.add(listener);
}
public void removeListener(MyListener listener) {
listeners.remove(listener);
}
public void triggerEvent(String message) {
for (MyListener listener : listeners) {
listener.onEventOccurred(message);
}
}
}
MyListenerImpl
的類:public class MyListenerImpl implements MyListener {
private String name;
public MyListenerImpl(String name) {
this.name = name;
}
@Override
public void onEventOccurred(String message) {
System.out.println(name + " received event: " + message);
}
}
public class Main {
public static void main(String[] args) {
EventPublisher publisher = new EventPublisher();
MyListenerImpl listener1 = new MyListenerImpl("Listener 1");
MyListenerImpl listener2 = new MyListenerImpl("Listener 2");
publisher.addListener(listener1);
publisher.addListener(listener2);
publisher.triggerEvent("Hello, listeners!");
}
}
運行這個程序,你將看到兩個監聽器都收到了事件通知。