1. 개요

Command 패턴은 행동을 캡슐화하여 요청자와 실행자를 분리하는 디자인 패턴입니다. 이 패턴은 행동을 객체로 만들어 동작의 실행, 취소, 재실행 등을 유연하게 관리할 수 있도록 돕습니다. ✨


2. 개념

Command 패턴의 핵심은 요청을 "명령" 객체로 감싸는 것입니다. 이를 통해 행동을 캡슐화하고, 다음과 같은 장점을 제공합니다:

  • 요청의 파라미터화: 행동을 객체로 표현하여 실행 타이밍을 유연하게 제어 가능.
  • 작업 큐 관리: 요청을 큐에 쌓아 순차적으로 처리 가능.
  • Undo/Redo: 이전 행동을 쉽게 취소하거나 반복 실행 가능.

구성 요소는 아래와 같습니다:

  1. Command 인터페이스: 실행 및 취소 동작을 정의.
  2. ConcreteCommand: 실제 동작 구현.
  3. Invoker: 명령을 실행하거나 취소.
  4. Receiver: 실제 행동을 수행하는 객체.

3. 예제

아래는 C#을 활용한 간단한 예제입니다. Unity3D에서도 동일한 원리로 활용 가능합니다.

요구사항

  • 캐릭터가 점프하거나 이동하는 행동을 Command 패턴으로 관리.

코드 구현

// Command 인터페이스
public interface ICommand
{
    void Execute();
    void Undo();
}

// Receiver
public class Character
{
    public void Jump() => Debug.Log("Character jumps");
    public void MoveLeft() => Debug.Log("Character moves left");
    public void MoveRight() => Debug.Log("Character moves right");
}

// ConcreteCommand
public class JumpCommand : ICommand
{
    private Character _character;

    public JumpCommand(Character character)
    {
        _character = character;
    }

    public void Execute() => _character.Jump();

    public void Undo() => Debug.Log("Undo Jump");
}

public class MoveCommand : ICommand
{
    private Character _character;
    private string _direction;

    public MoveCommand(Character character, string direction)
    {
        _character = character;
        _direction = direction;
    }

    public void Execute()
    {
        if (_direction == "left")
            _character.MoveLeft();
        else if (_direction == "right")
            _character.MoveRight();
    }

    public void Undo() => Debug.Log($"Undo Move {_direction}");
}

// Invoker
public class InputHandler
{
    private ICommand _command;

    public void SetCommand(ICommand command)
    {
        _command = command;
    }

    public void ExecuteCommand()
    {
        _command.Execute();
    }

    public void UndoCommand()
    {
        _command.Undo();
    }
}

// Usage
public class Game : MonoBehaviour
{
    void Start()
    {
        Character character = new Character();
        InputHandler inputHandler = new InputHandler();

        ICommand jumpCommand = new JumpCommand(character);
        ICommand moveLeftCommand = new MoveCommand(character, "left");

        inputHandler.SetCommand(jumpCommand);
        inputHandler.ExecuteCommand(); // Output: "Character jumps"

        inputHandler.SetCommand(moveLeftCommand);
        inputHandler.ExecuteCommand(); // Output: "Character moves left"

        inputHandler.UndoCommand(); // Output: "Undo Move left"
    }
}

4. 주의점 🚨

  • 명령 객체 증가: Command 패턴을 사용하면 행동마다 객체가 생성됩니다. 프로젝트 규모가 커질수록 관리가 복잡해질 수 있습니다.
  • 간단한 경우 비효율: 단순한 요청을 처리하기 위해 Command 패턴을 적용하면 오히려 코드가 복잡해질 수 있습니다. 상황에 맞게 사용해야 합니다.

5. 결론

Command 패턴은 행동을 객체로 캡슐화하여 요청과 실행을 분리하는 강력한 도구입니다. 특히 Undo/Redo 기능이나 작업 큐 관리가 필요한 경우 유용합니다. 하지만 모든 상황에서 적합한 것은 아니니, 복잡성과 효율성을 고려해 선택적으로 사용하는 것이 중요합니다. 💡


6. 관련 링크 🔗

반응형

+ Recent posts