package com.fujica.abk.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 事件总线
 */
public class EventBus {
    private static EventBus instance;
    private Map<String, List<EventListener>> listeners = new HashMap<>();

    private EventBus() {
    }

    public static EventBus getInstance() {
        if (instance == null) {
            synchronized (EventBus.class) {
                if (instance == null) {
                    instance = new EventBus();
                }
            }
        }
        return instance;
    }

    /**
     * 发送事件
     */
    public void emit(String event) {
        List<EventListener> eventListeners = listeners.get(event);
        if (eventListeners != null) {
            for (EventListener listener : eventListeners) {
                listener.onEvent(event);
            }
        }
    }

    /**
     * 订阅事件
     */
    public void on(String event, EventListener listener) {
        List<EventListener> eventListeners = listeners.get(event);
        if (eventListeners == null) {
            eventListeners = new ArrayList<>();
            listeners.put(event, eventListeners);
        }
        eventListeners.add(listener);
    }

    /**
     * 取消订阅
     */
    public void off(String event, EventListener listener) {
        List<EventListener> eventListeners = listeners.get(event);
        if (eventListeners != null) {
            eventListeners.remove(listener);
        }
    }

    /**
     * 事件监听器接口
     */
    public interface EventListener {
        void onEvent(String event);
    }
}

