메멘토 패턴(Memento Pattern)

 

객체의 상태를 이전 상태로 복원할 수 있는 기능을 제공하는 디자인 패턴이다.

 

이 패턴은 특히 게임 개발, 에디터, 복잡한 트랜잭션의 처리 등에서 사용자의 작업을 취소하거나 상태를 이전 상태로 되돌릴 필요가 있을 때 유용하다. 

 

ex) 뒤로가기 버튼

 

메멘토 패턴의 구성 요소

메멘토 패턴은 다음과 같은 세 가지 주요 구성 요소로 이루어져 있다.

 

  1. Originator: 원본 객체의 상태를 저장하거나 복원할 수 있는 기능을 가지고 있으며, 이 객체의 상태를 메멘토 객체에 저장하여 나중에 해당 상태로 복원한다.
  2. Memento: 원본 객체의 상태를 저장하는 객체이며, 이 객체는 원본 객체의 내부 상태를 캡슐화하여 외부에서 직접 접근할 수 없도록 한다.
  3. Caretaker: 메멘토 객체를 관리하는 객체로, 메멘토의 저장 및 복원을 담당한다. 하지만 메멘토 내부의 상태에는 접근하지 않는다.

 

 

<간단한 코드 예시>

[System.Serializable]
public class PositionMemento
{
    public float x, y, z;

    public PositionMemento(float x, float y, float z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }
}

1. Memento 클래스

using UnityEngine;

public class PlayerOriginator : MonoBehaviour
{
    // 플레이어의 현재 위치 상태를 저장합니다.
    public PositionMemento SaveToMemento()
    {
        return new PositionMemento(transform.position.x, transform.position.y, transform.position.z);
    }

    // 저장된 메멘토로부터 플레이어의 위치를 복원합니다.
    public void RestoreFromMemento(PositionMemento memento)
    {
        transform.position = new Vector3(memento.x, memento.y, memento.z);
    }
}

2. PlayerOriginator 클래스 (플레이어 위치 관리)

using System.Collections.Generic;

public class Caretaker
{
    private List<Memento> mementoList = new List<Memento>();

    public void Add(Memento state)
    {
        mementoList.Add(state);
    }

    public Memento Get(int index)
    {
        return mementoList[index];
    }
}

3. Caretaker 클래스

 

 

각 클래스를 다음과 같이 사용할 수 있다.

 

using System.Collections.Generic;
using UnityEngine;

public class Caretaker : MonoBehaviour
{
    private List<PositionMemento> savedPositions = new List<PositionMemento>();

    public void SavePosition(PositionMemento memento)
    {
        savedPositions.Add(memento);
    }

    public PositionMemento GetPosition(int index)
    {
        return savedPositions[index];
    }
}

 

 

플레이어의 위치를 저장하고 싶을 때 SavePosition 메소드를 호출하여 현재 위치를 저장,

 

이전 위치로 복원하고 싶을 때는 GetPosition 메소드로 저장된 위치를 가져와서

 

RestoreFromMemento 메소드를 호출하여 플레이어의 위치를 복원한다.

반응형

+ Recent posts