在Java中,为了实现事件解耦,我们可以采用以下几种方法:
public interface ActionListener {
void actionPerformed(ActionEvent e);
}
public class EventPublisher {
private List<ActionListener> listeners = new ArrayList<>();
public void addListener(ActionListener listener) {
listeners.add(listener);
}
public void removeListener(ActionListener listener) {
listeners.remove(listener);
}
public void fireEvent(ActionEvent e) {
for (ActionListener listener : listeners) {
listener.actionPerformed(e);
}
}
}
public class JButton extends JComponent {
private ActionListener actionListener;
public void setActionListener(ActionListener actionListener) {
this.actionListener = actionListener;
}
public void removeActionListener(ActionListener actionListener) {
this.actionListener = null;
}
// ... 其他代码
}
public class EventBus {
private static EventBus instance;
private Map<Class<?>, List<EventHandler<?>>> handlers = new HashMap<>();
private EventBus() {}
public static synchronized EventBus getInstance() {
if (instance == null) {
instance = new EventBus();
}
return instance;
}
public <T extends Event> void register(Class<T> eventType, EventHandler<T> handler) {
handlers.computeIfAbsent(eventType, k -> new ArrayList<>()).add(handler);
}
public <T extends Event> void unregister(Class<T> eventType, EventHandler<T> handler) {
List<EventHandler<?>> eventHandlers = handlers.get(eventType);
if (eventHandlers != null) {
eventHandlers.remove(handler);
}
}
public <T extends Event> void post(T event) {
List<EventHandler<?>> eventHandlers = handlers.get(event.getClass());
if (eventHandlers != null) {
for (EventHandler<?> handler : eventHandlers) {
handler.handle(event);
}
}
}
}
通过使用这些方法,我们可以实现Java ActionListener的事件解耦,使代码更加灵活和可维护。