6. UML Diagram
Originator
• 상태를 가지고 있는 클래스
• 현재의 상태를 가지는 메멘토 인스턴스 생성
• 메멘토 인스턴스를 사용하여 상태를 이전으로 돌림
Memento
Caretaker
• Memento를 관리하고 유지
• Memento의 내부엔 접근불가
• 한 시점의 상태를 저장하는 클래스
• Originator만 내부에 접근가능 함
7. UML Diagram
Originator = 남자(Man)
• 상태를 가지고 있는 클래스
• 현재의 상태를 가지는 메멘토 인스턴스 생성
• 메멘토 인스턴스를 사용하여 상태를 이전으로 돌림
Caretaker = 신 또는 작가(God)
• Memento를 관리하고 유지
• Memento의 내부엔 접근불가
Memento = 문신(Tattoo)
• 한 시점의 상태를 저장하는 클래스
• Originator만 내부에 접근가능 함
9. God Class(Caretaker)
public class God {
public static void main(String[] args) {
List<Tattoo> tattooList = new ArrayList<Tattoo>();
Man man = new Man("Leonard", 35);
!
man.introduceMyself(); // My name is Leonard and I'm 35 years old
man.resetMemory(); // 10분에 한번씩 호출하는 병에 걸림
man.introduceMyself(); // My name is null and I'm null years old
man.know("Leonard", 35);
tattooList.add(man.tattoo("Leonard", 35));
!
// 10분 후
man.resetMemory();
man.introduceMyself(); // My name is null and I'm null years old
man.seeTattoo(tattooList.get(0));
man.introduceMyself(); // My name is Leonard and I'm 35 years old
}
}
10. Man Class(Originator)
public class Man {
String name;
Integer age;
!
public Man(String name, Integer age) {
this.name = name;
this.age = age;
}
public void know(String name, int age) {
this.name = name;
this.age = age;
}
!
public void resetMemory() {
this.name = null;
this.age = null;
}
!
public Tattoo tattoo(String name, int age) {
Tattoo tattoo = new Tattoo(name, age);
return tattoo;
}
public void introduceMyself() {
System.out.println("My name is " + name +
" and I'm " + age + " years old");
}
public void seeTattoo(Tattoo tattoo) {
this.name = tattoo.getName();
this.age = tattoo.getAge();
}
}
11. Tattoo Class
public static class Tattoo {
private final String name;
private final int age;
public Tattoo(String name, int age) {
this.name = name;
this.age = age;
}
!
public Integer getAge() {
return age;
}
!
public String getName() {
return name;
}
}
12. Real World Example - Database Transaction
Memento Pattern을 사용하여 Rollback을 수행함.
13. Memento Pattern이 없었다면…
• Man Class가 과거의 상태를 다 가지고 있게돼서 코드가
복잡해졌을 것이다.
• 클래스가 하는 일이 많아져서 통제가 힘들어졌을 것이다.
• 상태를 저장하는 공간과 사용하는 공간이 같아서 안정성에
문제가 생겼을 것이다.
14. Memento Pattern이 있어서…
• Man(Originator)과 Tattoo(Memento)를 저장하는 공간이
분리되어 있어서 안전하게 저장 할 수 있다.
• 캡슐화를 위배하지 않고 내부 상태를 저장 할 수 있다.
• God(Caretaker)가 Tattoo(Memento)에 신경 안쓰고 저장
하고 복원 할 수 있다.
15. Command Pattern
• Memento Pattern과 함께 사용 될 수 있다.
• 다음 주에 함께 알아 보겠습니다.