모든 아이들이 인터페이스 하나를 상속받게 되어서 각자 상속받은 인터페이스의 메소드를 다른 방식으로 구현하도록 함.
추상팩토리/팩토리메서드 패턴과 결합해 사용한다고 생각해도됨. FSM 쓰면 이건 안써도됨. 간단하게 만드는 경우에는 전략패턴을 사용하면 스테이트머신을 안만들어도 되어서 그럴때 전략패턴을 사용함
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);
}
}
}'STUDY > 디자인패턴' 카테고리의 다른 글
| Mediator 메디에이터 패턴 (0) | 2024.07.19 |
|---|---|
| Memento 메멘토 패턴 ★ (0) | 2024.07.19 |
| Observer 옵저버 패턴 ★★★ (0) | 2024.07.19 |
| FSM(Finite-State-Machine) ★★★ (0) | 2024.07.17 |
| Command 커맨드 패턴 ★★★ (0) | 2024.07.16 |