๋ฐ์ํ
๐ฎ Unity ๋์์ธ ํจํด - ์ปค๋งจ๋(Command) ํจํด
1. ์ปค๋งจ๋ ํจํด์ด๋?
์ปค๋งจ๋(Command) ํจํด์ ์์ฒญ(ํ๋)์ ํ๋์ ๊ฐ์ฒด๋ก ์บก์ํํ์ฌ,
- ๋์ค์ ์คํํ๊ฑฐ๋
- ์ทจ์ํ๊ฑฐ๋
- ์ ์ฅํ๊ฑฐ๋
- ์ฌ๋ฌ ๋ช ๋ น์ ํ์ ์์๋์๋ค๊ฐ ์์ฐจ์ ์ผ๋ก ์คํํ ์ ์๋๋ก ๋์์ฃผ๋ ํจํด์ ๋๋ค.
"ํ๋์ ์ง์ ์ํํ์ง ์๊ณ , ๋ช ๋ น ์ชฝ์ง๋ฅผ ๋ง๋ค์ด์ ์ ๋ฌํ๋ ๋ฐฉ์"์ด๋ผ๊ณ ์๊ฐํ๋ฉด ์ดํด๊ฐ ์ฝ์ต๋๋ค.
2. ์ธ์ ์ฌ์ฉํ๋์?
- ํ๋(๋ช ๋ น)์ ์ฌ์ฌ์ฉํ๊ฑฐ๋ ๊ธฐ๋กํ๊ณ ์ถ์ ๋
- Undo/Redo, ๋งคํฌ๋ก ๋ช ๋ น, ๋ฆฌํ๋ ์ด ๊ธฐ๋ฅ์ ๋ง๋ค๊ณ ์ถ์ ๋
- UI ๋ฒํผ์ด๋ ํค ์ ๋ ฅ์ ๋์ํ๋ ๋ก์ง์ ์ ์ฐํ๊ฒ ์ฒ๋ฆฌํ๊ณ ์ถ์ ๋
3. ๊ตฌ์กฐ ๊ตฌ์ฑ์์
์ญํ | ์ค๋ช |
ICommand | ๋ช ๋ น์ ์ธํฐํ์ด์ค (Execute, Undo ๋ฑ) |
ConcreteCommand | ์ค์ ์คํ ๋ก์ง์ ๋ด์ ๋ช ๋ น ๊ฐ์ฒด |
Invoker | ๋ช ๋ น์ ์คํํ๋ ์ฃผ์ฒด (์: InputHandler, ๋ฒํผ ๋ฑ) |
Receiver | ๋ช ๋ น์ ์ค์ ์์ ์ ์ํํ๋ ๊ฐ์ฒด |
4. Unity ์์ : ํ๋ ์ด์ด ๋ช ๋ น ์์คํ
๐ฎ Step 1: ICommand ์ธํฐํ์ด์ค
public interface ICommand
{
void Execute();
void Undo();
}
๐งฑ Step 2: ์ค์ ๋ช ๋ น๋ค
public class MoveCommand : ICommand
{
private Player player;
public MoveCommand(Player p) => player = p;
public void Execute() => player.Move();
public void Undo() => player.Stop();
}
public class JumpCommand : ICommand
{
private Player player;
public JumpCommand(Player p) => player = p;
public void Execute() => player.Jump();
public void Undo() => Debug.Log("์ ํ ์ทจ์");
}
๐ง Step 3: ์์ ์(Receiver) - Player
using UnityEngine;
public class Player : MonoBehaviour
{
public void Move() => Debug.Log("ํ๋ ์ด์ด ์ด๋ ์ค...");
public void Jump() => Debug.Log("ํ๋ ์ด์ด ์ ํ!");
public void Stop() => Debug.Log("ํ๋ ์ด์ด ์ ์ง");
}
๐น๏ธ Step 4: ์ ๋ ฅ ํธ๋ค๋ฌ (Invoker)
using UnityEngine;
public class InputHandler : MonoBehaviour
{
public Player player;
private ICommand moveCommand;
private ICommand jumpCommand;
private void Start()
{
moveCommand = new MoveCommand(player);
jumpCommand = new JumpCommand(player);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.W))
moveCommand.Execute();
if (Input.GetKeyDown(KeyCode.Space))
jumpCommand.Execute();
}
}
5. ํ์ฅ: ๋ช ๋ น ํ์คํ ๋ฆฌ๋ก Undo ๊ตฌํํ๊ธฐ
using System.Collections.Generic;
public class CommandManager
{
private Stack<ICommand> history = new();
public void ExecuteCommand(ICommand command)
{
command.Execute();
history.Push(command);
}
public void UndoCommand()
{
if (history.Count > 0)
{
ICommand last = history.Pop();
last.Undo();
}
}
}
6. ์ ๋ฆฌ ๋ฐ ์ฅ๋จ์
โ ์ฅ์
- ๋ช ๋ น์ ๋์ค์ ์คํํ๊ฑฐ๋ ์ทจ์ ๊ฐ๋ฅ (Undo, Replay ๋ฑ)
- ๋ช ๋ น์ ๋ชจ๋ํํ์ฌ ํ์ฅ์ฑ ↑
- ์ ๋ ฅ → ํ๋์ ๋ถ๋ฆฌํ์ฌ ๊ด๋ฆฌํ๊ธฐ ์ฌ์
โ ๋จ์
- ํด๋์ค ์ ์ฆ๊ฐ
- ๋จ์ํ ์์ ์ ์ค๋ฒํค๋ ๋ฐ์
โ ๋ง๋ฌด๋ฆฌ ํ ์ค ์์ฝ
์ปค๋งจ๋ ํจํด์ ํ๋์ ๊ฐ์ฒด๋ก ๋ง๋ค๊ณ , ์คํ์ ์ ์ดํ๋ ๊ตฌ์กฐ๋ก, UI, ์ ๋ ฅ ์ฒ๋ฆฌ, ์คํ ๊ธฐ๋ก ๊ธฐ๋ฅ ๋ฑ์ ๋งค์ฐ ์ ํฉํ ํจํด์ ๋๋ค.
๋ฐ์ํ
'C# > DesignPattern' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
DesignPattern - ์ค์ฌ์(Mediator) ํจํด (1) | 2025.08.06 |
---|---|
DesignPattern - ์ ๋ต(Strategy) ํจํด (1) | 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 |