memento pattern (1)

Creational Patterns ( 생성 패턴 )

These design patterns provides way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. 

생성패턴은 객체의 생성로직을 숨기고 new 명령어를 통하지 않고 객체를 생성하는 방법들을 제공한다. 이는 특정 상황에서 어떤 방법으로 객체를 생성해야할지를 결정하는데 있어서 유연성을 제공한다. 


 Structural Patterns ( 구조적 패턴 )

These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. 

구조적 패턴들은 클래스와 객체의 구성에 관여한다.

 

 Behavioral Patterns ( 행위적 패턴 )

These design patterns are specifically concerned with communication between objects.

이 패턴들은 객체들 사이의 커뮤니케이션에 관심을 가진다.

 

오늘 살펴볼  Memento 패턴은 Behavioral 패턴에 속합니다. 

 

Memento Pattern Structure

 




  

패턴의 목적 ( Intent ) :  

Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.


패턴이 나오게 된 동기 ( Motivation ) :

    다이어그램을 그리는 툴을 예로 들어보겠습니다. 사각형 두개를 그리고 두 사각형을 선으로 연결합니다. 자 이제 아래쪽 사각형을 오른쪽으로 이동시킵니다. 그러면 아래 그림처럼 두 사각형을 이은 선도 따라서 이동하면서 두 사각형을 계속 이어줍니다.  


이렇게 두 객체 사이의 연결 관계를 유지시키는 잘 알려진 방법중 하나는 제약-해결 시스템(constraint-solving system)입니다. 이 시스템은 ConstraintSolver 에 캡슐화되어 있습니다. ConstraintSolver는 객체들 사이의 연결을 기록하고 이 연결을 설명하는 수학식을 생성합니다. 그래서 객체의 위치가 변경이 되면 이 수학식을 다시 계산하여 선을 어떻게 그려야 하는지를 알 수 있는 것입니다.

 

하 지만 되돌리기 기능은 생각처럼 쉽지가 않습니다. 만약 사각형이 움직인 거리를 계산하여 그만큼 다시 되돌린다고 했을 때 과연 두 사각형을 연결하는 선은 어떻게 움직여야 하는가를 생각해야 합니다. 그렇지 않으면 아래와 같이 불완전한 되돌리기가 되어버릴 테니까요.

 

일 반적으로 ConstraintSolver의 public interface 는 undo기능을 완전히 구현하기에 불충분합니다. undo 메카니즘은 이전의 상태를 다시 불러오기 위해서 ConstraintSolver와 좀 더 밀접한 관계를 맺어야 하지만 한편으로는 ConstraintSolver의 내부를 노출시키면 안됩니다. 이 문제를 풀기위해서 나온 패턴이 바로 메멘토 패턴입니다. 메멘토는 다른 객체(메멘토의 originator)의 내부 상태를 저장하는 객체입니다. undo 메타니즘은 originator의 이전 상태가 필요할 때 메멘토를 요청하게 됩니다. originator는 자신의 현재 상태를 메멘토에 저장합니다. 그리고 오로지 originator만이 메멘토에 저장한 자신의 상태를 저장 또는 읽어올 수가 있습니다 — 메멘토는 다른 객체들에게 "오파크(침투할 수 없는 것)"라고 할 수 있죠. 위에서 예로 든 툴에서 ConstraintSolver는 originator의 역할을 하는거죠.  

 

The following sequence of events characterizes theundo process:

      1. The editor requests a memento from the ConstraintSolver as aside-effect of the move operation.

      2. The ConstraintSolver creates and returns a memento, an instance of a class SolverState in this case. A SolverState memento contains data structures that describe the current state of the ConstraintSolver's internal equations and variables.

      3. Later when the user undoes the move operation, the editor gives the SolverState back to the ConstraintSolver.

      4. Based on the information in the SolverState, the ConstraintSolver changes its internal structures to return its equations and variables to their exact previous state.

This arrangement lets the ConstraintSolver entrust other objects with the information it needs to revert to a previous state without exposing its internal structure and representations.



유용성 ( Applicability ) :

 

Use the Memento pattern when

    • a snapshot of (some portion of) an object's state must be saved so that it can be restored to that state later, and

    • a direct interface to obtaining the state would expose implementation details and break the object's encapsulation.



등장 인물 ( Participants ) :


Memento (SolverState)

o stores internal state of the Originator object. The memento may store as much or as little of the originator's internal state as necessary at its originator's discretion.
o protects against access by objects other than the originator. Mementos have effectively two interfaces. Caretaker sees a narrow interface to the Mementoit can only pass the memento to other objects. Originator, in contrast, sees a wide interface, one that lets it access all the data necessary to restore itself to its previous state. Ideally, only the originator that produced the memento would be permitted to access the memento's internal state.

Originator (ConstraintSolver)

o creates a memento containing a snapshot of its current internal state.
o uses the memento to restore its internal state.

Caretaker (undo mechanism)

o is responsible for the memento's safekeeping.
o never operates on or examines the contents of a memento.

 

 

원리 ( Collaborations ) :  

A caretaker requests a memento from an originator, holds it for a time, and passes it back to the originator, as the following interaction diagram illustrates:   



 

 

Sometimes the caretaker won't pass the memento back to the originator, because the originator might never need to revert to an earlier state.

Mementos are passive. Only the originator that created a memento will assign or retrieve its state.

 


패턴 사용법

    1. Identify the roles of “caretaker” and “originator”.
    2. Create a Memento class and declare the originator a friend.
    3. Caretaker knows when to "check point" the originator.
    4. Originator creates a Memento and copies its state to that Memento.
    5. Caretaker holds on to (but cannot peek into) the Memento.
    6. Caretaker knows when to "roll back" the originator.
    7. Originator reinstates itself using the saved state in the Memento.

패턴 사용의 장단점 ( Consequences ): 

The Memento pattern has several consequences:

 

    1. Preserving encapsulation boundaries. Memento avoids exposing information that only an originator should manage but that must be stored nevertheless outside the originator. The pattern shields other objects from potentially complex Originator internals, thereby preserving encapsulation boundaries.

    2. It simplifies Originator. In other encapsulation-preserving designs, Originator keeps the versions of internal state that clients have requested. That puts all the storage management burden on Originator. Having clients manage the state they ask for simplifies Originator and keeps clients from having to notify originators when they're done.

    3. Using mementos might be expensive. Mementos might incur considerable overhead if Originator must copy large amounts of information to store in the memento or if clients create and return mementos to the originator often enough. Unless encapsulating and restoring Originator state is cheap, the pattern might not be appropriate.

    4. Defining narrow and wide interfaces. It may be difficult in some languages to ensure that only the originator can access the memento's state.

    5. Hidden costs incaring for mementos. A caretaker is responsible for deleting the mementos it cares for. However, the caretaker has no idea how much state is in the memento. Hence an otherwise lightweight caretaker might incur large storagecosts when it stores mementos.


관련 패턴들 :  

 

Command : Commands can use mementos to maintain state for undoable operations.  

Iterator : Mementos can be used for iteration as described earlier.



추가 정보 :       

    • Command and Memento act as magic tokens to be passed around and invoked at a later time. In Command, the token represents a request; in Memento, it represents the internal state of an object at a particular time. Polymorphism is important to Command, but not to Memento because its interface is so narrow that a memento can only be passed as a value.
    • Command can use Memento to maintain the state required for an undo operation.
    • Memento is often used in conjunction with Iterator. An Iterator can use a Memento to capture the state of an iteration. The Iterator stores the Memento internally.

 

 


 

출처 :  http://sourcemaking.com/design_patterns/memento

Design Patterns : Element of Reusable Object Oriented Software ( by GoF, 1994 )