๋ฐ์ํ
๐งฉ Unity ๋์์ธ ํจํด - ์ค์ฌ์(Mediator) ํจํด
1. ์ค์ฌ์ ํจํด์ด๋?
์ค์ฌ์(Mediator) ํจํด์ ๊ฐ์ฒด ๊ฐ์ ์ง์ ์ ์ธ ์ํต์ ํผํ๊ณ , ๋ชจ๋ ํต์ ์ ์ค์ ๊ด๋ฆฌ์(์ค์ฌ์)๋ฅผ ํตํด ์งํํ๋๋ก ์ค๊ณํ๋ ํจํด์ ๋๋ค.
"A์ B๊ฐ ์๋ก๋ฅผ ๋ชฐ๋ผ๋, ์ค์ฌ์์๊ฒ๋ง ๋งํ๋ฉด ํ์ํ ์ฐ๊ฒฐ์ด ์๋์ผ๋ก ์ด๋ค์ง๋ ๊ตฌ์กฐ"์ ๋๋ค.
2. ์ธ์ ์ฌ์ฉํ๋์?
- UI ์์๋ ์์คํ ๊ฐ ์ํธ์์ฉ์ด ๋ง๊ณ ๋ณต์กํ ๋
- ๊ฐ์ฒด ๊ฐ ๊ฒฐํฉ๋๋ฅผ ๋ฎ์ถ๊ณ ์ถ์ ๋
- Observer ํจํด๋ณด๋ค ๋ ๋์ ๋ฒ์์ ์ ์ด๊ฐ ํ์ํ ๋
3. ๊ตฌ์กฐ ๊ตฌ์ฑ์์
์ญํ | ์ค๋ช |
IMediator | ์ค์ฌ์ ์ธํฐํ์ด์ค |
ConcreteMediator | ์ค์ ์ด๋ฒคํธ๋ฅผ ์ค๊ณํ๋ ํด๋์ค |
Participant | ์ค์ฌ์์๊ฒ ๋ฉ์์ง๋ฅผ ๋ณด๋ด๋ ๊ตฌ์ฑ์ ๊ฐ์ฒด |
4. Unity ์์ : ๋ฒํผ ๋๋ฅด๋ฉด ์ฌ๋ฌ ์์คํ ์ ๋ช ๋ น ์ ํ
๐ฌ Step 1: IMediator ์ธํฐํ์ด์ค
public interface IMediator
{
void Notify(string eventKey, object data = null);
}
๐ง Step 2: ConcreteMediator ํด๋์ค
using System;
using System.Collections.Generic;
public class GameMediator : IMediator
{
private Dictionary<string, Action<object>> listeners = new();
public void Register(string eventKey, Action<object> callback)
{
if (!listeners.ContainsKey(eventKey))
listeners[eventKey] = delegate { };
listeners[eventKey] += callback;
}
public void Unregister(string eventKey, Action<object> callback)
{
if (listeners.ContainsKey(eventKey))
listeners[eventKey] -= callback;
}
public void Notify(string eventKey, object data = null)
{
if (listeners.TryGetValue(eventKey, out var callback))
callback?.Invoke(data);
}
}
๐ฆ Step 3: MediatorProvider (์ฑ๊ธํค ๋ฑ๋ก์)
public static class MediatorProvider
{
public static GameMediator Mediator = new();
}
๐งฑ Step 4: Button ํด๋ฆญ → ์ค์ฌ์์๊ฒ ์๋ฆผ
using UnityEngine;
public class UIButton : MonoBehaviour
{
public void OnClick()
{
MediatorProvider.Mediator.Notify("PlayClicked", "๊ฒ์ ์์!");
}
}
๐ฅ๏ธ Step 5: UIManager๊ฐ ์ด๋ฒคํธ ์์
using UnityEngine;
public class UIManager : MonoBehaviour
{
private void OnEnable()
{
MediatorProvider.Mediator.Register("PlayClicked", OnPlayClicked);
}
private void OnDisable()
{
MediatorProvider.Mediator.Unregister("PlayClicked", OnPlayClicked);
}
private void OnPlayClicked(object data)
{
Debug.Log($"UIManager ์์ : {data}");
// ์: ํ์ดํ ํ๋ฉด ์จ๊ธฐ๊ธฐ
}
}
5. ์ ๋ฆฌ ๋ฐ ์ฅ๋จ์
โ ์ฅ์
- ๊ฐ์ฒด ๊ฐ ์ง์ ์ฐธ์กฐ ์์ด ์ํธ์์ฉ ๊ฐ๋ฅ → ๊ฒฐํฉ๋ ↓
- ๋์ ์ผ๋ก ๊ตฌ๋ /ํด์ ๊ฐ๋ฅ
- ๋ณต์กํ ์์คํ ๊ฐ ํต์ ๊ตฌ์กฐ ๋จ์ํ
โ ๋จ์
- ๋ชจ๋ ํต์ ์ด ์ค์ฌ์๋ฅผ ๊ฑฐ์น๊ธฐ ๋๋ฌธ์, ์ค์ฌ์๊ฐ ๋น๋ํด์ง ์ ์์
- ๋๋ฒ๊น ์ ํ๋ฆ ์ถ์ ์ด ์ด๋ ค์์ง ์ ์์
โ ๋ง๋ฌด๋ฆฌ ํ ์ค ์์ฝ
์ค์ฌ์ ํจํด์ ๋ชจ๋ ๊ฐ์ฒด๊ฐ ์๋ก๋ฅผ ๋ชฐ๋ผ๋, ํ๋์ ์ฐฝ๊ตฌ๋ง ์๋ฉด ํ๋ ฅํ ์ ์๋ ์ค๊ณ๋ก, ๋ณต์กํ ์์คํ ๊ตฌ์กฐ๋ฅผ ๊น๋ํ๊ฒ ์ ๋ฆฌํ ์ ์๋ ๊ฐ๋ ฅํ ๋๊ตฌ์ ๋๋ค.
๋ฐ์ํ
'C# > DesignPattern' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
DesignPattern - ์ ๋ต(Strategy) ํจํด (1) | 2025.08.06 |
---|---|
DesignPattern - ์ปค๋งจ๋(Command) ํจํด (0) | 2025.08.06 |
DesignPattern - ์ํ ํจํด(State Pattern) vs FSM (2) | 2025.08.06 |
DesignPattern - ์ด๋ฒคํธ ๋ฒ์ค(Event Bus) ํจํด (0) | 2025.08.06 |
DesignPattern - ํฉํ ๋ฆฌ(Factory) ํจํด (1) | 2025.08.06 |