TIL(Today I Learned)

중간 점검 : EventManager는 어떻게 동작하는가

Najdorf 2024. 1. 10. 20:19
728x90

 

AddListener로 해당 이벤트 사용하겠다 선언
-> (해당 이벤트가 동작하면) 상속받은 OnEvent 메서드에서 관련 동작 수행

해당 이벤트가 동작하는 것을 알리려면
PostEvent로 해당 이벤트가 수행됐음을 나타냄
-> 해당 이벤트를 Listener로 등록한 모든 클래스의 OnEvent 실행

 

예시)

EventManager.Instance.AddListener(EventType.eGameEnd, this);


= 'eGameEnd'라는 이벤트가 동작하면,

OnEvent를 실행하겠다 라고 지금 클래스에 등록

EventManager.Instance.PostEvent(EventType.eItemChage, data);


= 'eItemChange' 라는 이벤트를 등록한 모든 클래스에게 동작했음을 알리고,
같이 넣은 data 정보도 함께 제공해준다 (안 넣으면 null).

 

 

EventManager.cs 전체 코드

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public enum EventType
{
    eUpdateItem,
    eGetItem,
    eGameEnd
}

public interface IListener
{
    void OnEvent(EventType type, object data);
}

namespace TextRPG
{
    internal class EventManager
    {
        private static readonly EventManager instance = new EventManager();

        static EventManager() { }
        private EventManager() { }

        public static EventManager Instance { get { return instance; } }
        private Dictionary<EventType, List<IListener>> listener = [];

        public void AddListener(EventType eventType, IListener _listener)
        {
            List<IListener>? listenList = null;

            if (listener.TryGetValue(eventType, out listenList))
            {
                listenList.Add(_listener);
                return;
            }

            listenList = [_listener];
            listener.Add(eventType, listenList);
        }

        public void PostEvent(EventType eventType, object? param = null)
        {
            List<IListener>? listenList;
            if (listener.TryGetValue(eventType, out listenList) == false)
                return;

            for (int i = 0; i < listenList.Count; i++)
            {
                listenList?[i].OnEvent(eventType, param);
            }
        }

        public void RemoveListener(EventType eventType)
        {
            Dictionary<EventType, List<IListener>> newListeners = [];

            foreach (KeyValuePair<EventType, List<IListener>> item in listener)
            {
                for (int i = item.Value.Count - 1; i >= 0; i--)
                {
                    if (item.Value[i].Equals(null))
                        item.Value.RemoveAt(i);
                }

                if (item.Value.Count > 0)
                    newListeners.Add(item.Key, item.Value);
            }

            listener = newListeners;
        }

    }
}
728x90