옵저버 패턴은 다음 구조를 가진 디자인 패턴이다.
- 주체 : 상태 변화가 일어나는 쪽
- 옵저버 : 그 변화를 감지하고 반응하는 쪽
- 주체가 변화가 있을 때 , 옵저버들에게 자동으로 알림을 보낸다
- 여러 UI 가 같은 데이터를 구독해도 결합도가 낮아 유지보수가 쉬워진다
옵저버 패턴을 활용하여 스톱워치를 만들어보자
using UnityEngine;
using System;
public class TimerManager : MonoBehaviour
{
public static TimerManager _instance;
public event Action<float> OnTimeChanged;
private float _time;
private bool _isRunning = false;
private void Awake()
{
_instance = this;
}
private void Update()
{
if(!_isRunning)
{
return;
}
_time += Time.deltaTime;
Debug.Log("Timer Running: " + _time);
OnTimeChanged?.Invoke(_time);
}
public void StartTimer()
{
_isRunning = true;
}
public void StopTimer()
{
_isRunning = false;
}
public void ResetTimer()
{
_time = 0f;
OnTimeChanged?.Invoke(_time);
}
}
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class TimerUI : MonoBehaviour
{
[SerializeField] private TextMeshProUGUI _timerText;
private void Start()
{
if(TimerManager._instance != null)
{
TimerManager._instance.OnTimeChanged += UpdateTimerUI;
}
}
private void OnDestroy()
{
if(TimerManager._instance != null)
{
TimerManager._instance.OnTimeChanged -= UpdateTimerUI;
}
}
private void UpdateTimerUI(float time)
{
int minutes = Mathf.FloorToInt(time / 60);
int seconds = Mathf.FloorToInt(time % 60);
_timerText.text = $"{minutes:00}:{seconds:00}";
}
}
이 코드에서 구조가 어떻게 적용되었나?
public event Action<float> OnTimeChanged;
이 이벤트가 바로 구독자들에게 변화 알려주는 수단
_time 값이 변할 때마다 이벤트를 호출함
OnTimeChanged?.Invoke(_time);
상태 변화 발생 - 모든 구독자에게 알림 전파
구독자
TimerManager._instance.OnTimeChanged += UpdateTimerUI;
TimerUI 는 TimerManager 가 발행하는 이벤트를 구독
시간이 변경될 때마다 TimerManager 가 호출해주는 UpdateTimerUI 를 실행
'📖TIL' 카테고리의 다른 글
| 251210 Github Issue & Github Projects (0) | 2025.12.10 |
|---|---|
| 251209 CSV 파싱 (0) | 2025.12.09 |
| 251204 (0) | 2025.12.04 |
| 251203 (0) | 2025.12.03 |
| 251202 (0) | 2025.12.02 |