-
[Design Pattern] 메멘토 패턴 (Memento Pattern)공부/디자인 패턴 2021. 7. 17. 21:11
메멘토 패턴이란 객체의 정보를 저장하고 사용자가 원하는 시점의 데이터를 복원할 수 있도록 하는 패턴입니다.
클래스 다이어그램
Originator: 현재 상태를 저장하고 Memento 객체의 정보를 얻는 클래스
Memento: 상태를 갖고 있는 클래스
Caretaker: Memento 클래스를 순서대로 저장하는 클래스
예제
public class Memento { private final String state; public Memento(String state){ this.state = state; } public String getState(){ return state; } } public class Originator { private String state; public void setState(String state){ this.state = state; } public String getState(){ return state; } public Memento saveStateToMemento(){ return new Memento(state); } public void getStateFromMemento(Memento memento){ state = memento.getState(); } } public class CareTaker { private final List<Memento> mementoList = new ArrayList<>(); public void add(Memento state){ mementoList.add(state); } public Memento get(int index){ return mementoList.get(index); } } Originator originator = new Originator(); CareTaker careTaker = new CareTaker(); originator.setState("State #1"); originator.setState("State #2"); careTaker.add(originator.saveStateToMemento()); originator.setState("State #3"); careTaker.add(originator.saveStateToMemento()); originator.setState("State #4"); System.out.println("Current State: " + originator.getState()); originator.getStateFromMemento(careTaker.get(0)); System.out.println("First saved State: " + originator.getState()); originator.getStateFromMemento(careTaker.get(1)); System.out.println("Second saved State: " + originator.getState()); // Current State: State #4 // First saved State: State #2 // Second saved State: State #3
파이썬
class Memento: def __init__(self, state): self._state = state @property def state(self): return self._state class Originator: def __init__(self): self._state = None @property def state(self): return self._state @state.setter def state(self, state): self._state = state def create_memento(self): return Memento(self.state) def get_memento_state(self, memento): self._state = memento.state class CareTaker(list): pass originator = Originator() care_taker = CareTaker() originator.state = "State #1" originator.state = "State #2" care_taker.append(originator.create_memento()) originator.state = "State #3" care_taker.append(originator.create_memento()) originator.state = "State #4" print(f"Current State: {originator.state}") originator.get_memento_state(care_taker[0]) print(f"First saved State: {originator.state}") originator.get_memento_state(care_taker[1]) print(f"Second saved State: {originator.state}") # Current State: State #4 # First saved State: State #2 # Second saved State: State #3