프로젝트를 진행하면서 커맨드 패턴을 적용해보자는 기능이 있었다.
캠프 중에 특강을 통해서 이론적으로는 커맨드 패턴을 알고 있지만
실제로 구현해서 프로젝트에 적용하는 것은 이번이 처음이므로 공부를 해보고 작업을 하려고 한다.
public interface ICommand
{
void Execute();
void Undo();
}
using UnityEngine;
public class MoveCommand : ICommand
{
public CommandReceiver subject;
public Vector3 movement;
// 구체적인 명령들
public MoveCommand(CommandReceiver s, Vector3 move)
{
subject = s;
movement = move;
}
public void Execute()
{
Debug.Log("이동 명령 수행");
subject.Move(movement);
}
public void Undo()
{
Debug.Log("이동 명령 되돌리기");
subject.Move(-movement);
}
}
public class AttackCommand : ICommand
{
public CommandReceiver subject;
public GameObject target;
public float damage;
// 구체적인 명령들
public AttackCommand(CommandReceiver s, GameObject t, float d)
{
subject = s;
target = t;
damage = d;
}
public void Execute()
{
Debug.Log("공격 명령 수행");
subject.Attack(target, damage);
}
public void Undo()
{
Debug.Log("공격 명령 되돌리기");
}
}
using System.Collections.Generic;
using UnityEngine;
public class CommandInvoker : MonoBehaviour
{
// 명령 발송자, 히스토리 보관소
public Stack<ICommand> history = new Stack<ICommand>();
public void ExecuteCommand(ICommand command)
{
command.Execute();
history.Push(command);
}
public void UndoCommand()
{
if(history.Count > 0)
history.Pop().Undo();
}
}
using UnityEngine;
public class CommandReceiver : MonoBehaviour
{
// 명령을 수행할 클래스들
// 게임 캐릭터들
public void Move(Vector3 movement)
{
Debug.Log($"Move called {movement}");
}
public void Attack(GameObject go, float damage)
{
Debug.Log($"{gameObject.name}이/가 {go.name}에게 {damage}만큼 피해를 주었다.");
}
}
#내일배움캠프 #스파르타내일배움캠프 #스파르타내일배움캠프TIL