옵저버 패턴은 주체 역할 오브젝트 하나, 관찰자 역할 오브젝트 여러개, 즉 객체 사이의 일대다 의존 관계를 정의하며, 한 객체의 상태 변화가 다른 객체들에게 자동으로 통지되도록 한다. 주로 이벤트 처리나 상태 변화를 감지하고 그에 따라 반응할 때 사용된다.
구성 요소
- Subject (주체): 상태가 변경될 때 옵저버들에게 알리는 역할을 한다. 주로 이벤트 발생자 역할을 하며, 옵저버가 등록되고 제거되는 메서드를 포함한다.
- Observer (옵저버): Subject의 상태 변화를 관찰하고 필요에 따라 특정 동작을 수행하는 객체. Subject에서 발생한 변화에 대해 업데이트를 받아 처리한다.

using System.Collections.Generic;
using UnityEngine;
// 옵저버 인터페이스
public interface IObserver
{
void OnNotify(string message);
}
// 주체(Subject) 클래스
public class Subject : MonoBehaviour
{
private List<IObserver> observers = new List<IObserver>();
// 옵저버 등록
public void AddObserver(IObserver observer)
{
observers.Add(observer);
}
// 옵저버 제거
public void RemoveObserver(IObserver observer)
{
observers.Remove(observer);
}
// 모든 옵저버에게 알림
protected void NotifyObservers(string message)
{
foreach (var observer in observers)
{
observer.OnNotify(message);
}
}
}
// 구체적인 주체 클래스 예시 (플레이어)
public class Player : Subject
{
private int health = 100;
public void TakeDamage(int damage)
{
health -= damage;
NotifyObservers($"Player health changed to {health}");
if (health <= 0)
{
NotifyObservers("Player died");
}
}
}
// 구체적인 옵저버 클래스 예시 (UI)
public class HealthUI : MonoBehaviour, IObserver
{
public void OnNotify(string message)
{
Debug.Log($"HealthUI received: {message}");
// 여기서 UI를 업데이트한다.
}
}
// 구체적인 옵저버 클래스 예시 (UI)
public class PartyMemberNotify : MonoBehaviour, IObserver
{
public void OnNotify(string message)
{
Debug.Log($"HealthUI received: {message}");
// 여기서 UI를 업데이트한다.
}
}
// 사용 예시
public class ObserverExample : MonoBehaviour
{
private Player _player;
void Start()
{
_player = gameObject.AddComponent<Player>();
HealthUI healthUI = gameObject.AddComponent<HealthUI>();
PartyMemberNotify partyMemberNotify = gameObject.AddComponent<PartyMemberNotify>();
_player.AddObserver(healthUI);
_player.AddObserver(partyMemberNotify);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
// 플레이어가 데미지를 받으면 모든 옵저버에게 알림
_player.TakeDamage(20);
}
}
}
Subject 클래스 옵저버들을 관리하며 AddObserver, RemoveObserver 메서드로 옵저버를 추가하거나 제거할 수 있다. Player 클래스는 Subject를 상속받는 주체 역할이며 플레이어가 데미지를 받을때마다 TakeDamage가 호출되며 상태 변화를 옵저버들에게 알린다.
HealthUI클래스의 OnNotify 메서드로 주체로부터 연락을 받아 UI를 업데이트한다.
특정 키(A) 입력에 따라 플레이어가 데미지를 받도록하고 이에 대한 상태변화를 모든 옵저버들에게 알린다.

옵저버 패턴은 UI 업데이트, 게임 이벤트 처리, 플레이어 상태 관리 등 유용하게 사용되며 옵저버 간의 느슨한 결합을 통해 코드의 유지보수성과 확장성을 높일 수 있다.
'개인 공부 > 디자인패턴' 카테고리의 다른 글
| 유니티 중재자 (Mediator) (0) | 2024.07.19 |
|---|---|
| 유니티 메멘토 (1) | 2024.07.19 |
| 유니티 FSM (0) | 2024.07.17 |
| 디자인패턴 커맨드 & 유니티 커스텀 에디터 (1) | 2024.07.16 |
| 디자인패턴 책임 연쇄 패턴 (Chain of Responsibility) (0) | 2024.07.16 |