Command Pattern 의 장단점
CommandBase : CommandConcrete 라는 Class 를 생성 할 때 반드시 상속받는 abstract Class 이다
(단 필요에 따라 Abstaract Class 가 아니라 Interface 로도 쓸 수 있음)
필자는 Interface를 선호함
CommandConcrete : 구체적인 Command 기능이 있는 Class이다
Invoker(호출자) : 명령을 실행하는 방법을 안다
샘플 코드
예시로 쿠키런의 리플레이 기능을 만들어보려고 한다. Commandconcrete : Jump, Run, Dead CommandBase : Execute() Invoker : Execute
public abstract class CommandBase
{
public abstract void Execute();
}
public class CommandJump : CommandBase
{
public override void Execute()
{
Console.WriteLine("Jump");
}
}
public class CommandRun : CommandBase
{
public override void Execute()
{
Console.WriteLine("Run");
}
}
public class CommandDead : CommandBase
{
public override void Execute()
{
Console.WriteLine("Dead");
}
}
namespace CookieSpace
{
public class Invoker : MonoBehaviour
{
private CommandBase jumpCommand, deadCommand, runCommand;
private void Awake()
{
jumpCommand = new CommandJump();
runCommand = new CommandRun();
deadCommand = new CommandDead();
}
private void Update()
{
if (Input.GetKeyUp(KeyCode.Space))
ExecuteCommand(jumpCommand);
if (Input.GetKeyUp(KeyCode.LeftShift))
ExecuteCommand(runCommand);
if (Input.GetKeyUp(KeyCode.P))
ExecuteCommand(deadCommand);
}
public void ExecuteCommand(CommandBase command)
{
command.Execute();
}
}
public class Replay : MonoBehaviour
{
private SortedList<float, CommandBase> recordList = new SortedList<float, CommandBase>();
private float recordingTime = 0f;
private bool isRecord = true;
private CommandBase jumpCommand, deadCommand, runCommand;
private void Awake()
{
RecordStart();
jumpCommand = new CommandJump();
runCommand = new CommandRun();
deadCommand = new CommandDead();
}
private void Update()
{
if (!isRecord)
return;
if (Input.GetKeyUp(KeyCode.Space))
recordList.Add(recordingTime, jumpCommand);
if (Input.GetKeyUp(KeyCode.LeftShift))
recordList.Add(recordingTime, runCommand);
if (Input.GetKeyUp(KeyCode.P))
recordList.Add(recordingTime, deadCommand);
}
private void FixedUpdate()
{
if (isRecord)
recordingTime += Time.fixedDeltaTime;
}
public void RecordStart()
{
isRecord = true;
recordingTime = 0f;
}
}
}
대안
나의 선택
Command Pattern 이 쓸모없다는 소리는 아니지만 코드량을 줄이기 위해서 Stack, Qeueue 를 이용한 시퀀싱을 만들겠다