Command Pattern

순후추·2023년 11월 15일
0

디자인패턴

목록 보기
8/11

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;
     }
 }
}

대안

  • Queue, Stack : 큐 또는 스택을 사용해서 리플레이, 시퀀싱 시스템을 구현 할 수 있다.
  • Memento Pattern : Memento Pattern는 이전상태로 되돌리는 기능을 하는 디자인패턴이다.

나의 선택

Command Pattern 이 쓸모없다는 소리는 아니지만 코드량을 줄이기 위해서 Stack, Qeueue 를 이용한 시퀀싱을 
만들겠다
profile
게임 개발 블로그

0개의 댓글

관련 채용 정보