Showing posts with label Memento Pattern. Show all posts
Showing posts with label Memento Pattern. Show all posts

Sunday, 24 November 2013

Memento Design pattern - Implementation

🚀 Master Java Design Patterns & Software Architecture!

Subscribe to Ram N Java for clean software architecture patterns, design pattern deep dives, and production-ready implementation guides!

🔔 Subscribe to Ram N Java

Implementing the Memento Design Pattern in Java

In modern application design, preserving and restoring previous states—such as implementing undo/redo functionality, transactional rollbacks, or snapshot checkpoints—is a common necessity. However, exposing internal fields to external objects breaks encapsulation. The Memento Design Pattern solves this challenge cleanly by capturing and externalizing an object’s internal state so that it can be restored later without violating data encapsulation boundaries.

Key Components & Architecture

  • Originator: The core object containing the active state. It creates a snapshot of its internal state into a Memento object and restores its state when supplied with a previously saved Memento.
  • Memento: An immutable value object that securely encapsulates the internal state of the Originator. It provides restricted visibility to protect state data from unauthorized modification.
  • Caretaker: Responsible for tracking and storing Memento instances (e.g., maintaining an undo stack or history list) without inspecting or modifying the contents of the mementos.

Implementation Best Practices & Guidelines

  1. Protect Encapsulation: Ensure the Memento provides a wide interface to the Originator (allowing full state extraction/restoration) and a narrow interface to the Caretaker (preventing access to internal state variables).
  2. Enforce Immutability: Design Memento objects as immutable state containers so saved checkpoints cannot be altered after creation.
  3. Manage State Footprint: Storing full snapshots can consume significant memory. For large objects, consider delta-based state capture or limiting the history stack capacity.
  4. Leverage Inner Classes: Defining the Memento as a private inner class within the Originator allows seamless private field access while keeping the state strictly inaccessible to external consumers.

Why Proper Implementation Matters

  • Zero Encapsulation Violation: Internal state details remain strictly private to the Originator, keeping class boundaries pristine.
  • Simplified Originator Architecture: The Originator does not need to manage history management, stack structures, or archival logic—the Caretaker handles these lifecycle operations.
  • Predictable Undo/Redo Mechanisms: Simplifies complex multi-step state rollbacks across enterprise desktop, mobile, and web applications.

Recommended Next Videos

Continue your deep dive into the Memento pattern and behavioral design patterns with these related tutorials from our channel:


Click here to watch in Youtube : https://www.youtube.com/watch?v=ZjouanHQmdk

Click the below Image to Enlarge
Memento Design pattern - Implementation
Memento Design pattern - Class Diagram








































LedTV.java

public class LedTV
{
private String  size;
private String  price;
private boolean usbSupport;

public LedTV( String size, String price, boolean usbSupport )
{
super();
this.size = size;
this.price = price;
this.usbSupport = usbSupport;
}

public String getSize()
{
return size;
}

public void setSize( String size )
{
this.size = size;
}

public String getPrice()
{
return price;
}

public void setPrice( String price )
{
this.price = price;
}

public boolean isUsbSupport()
{
return usbSupport;
}

public void setUsbSupport( boolean usbSupport )
{
this.usbSupport = usbSupport;
}

@Override
public String toString()
{
return "LedTV [size=" + size + ", price=" + price + ", usbSupport=" + usbSupport + "]";
}

}


Memento.java

public class Memento
{
private LedTV ledTV;

public Memento( LedTV ledTV )
{
super();
this.ledTV = ledTV;
}

public LedTV getLedTV()
{
return ledTV;
}

public void setLedTV( LedTV ledTV )
{
this.ledTV = ledTV;
}

@Override
        public String toString()
        {
       return "Memento [ledTV=" + ledTV + "]";
        }

}

Caretaker.java

import java.util.ArrayList;
import java.util.List;
/*
 * Store Room
 */
public class Caretaker
{
private List<Memento> ledTvList = new ArrayList<Memento>();

public void addMemento( Memento m )
{
ledTvList.add(m);
System.out.println("LED TV's snapshots Maintained by CareTaker :" + ledTvList);
}

public Memento getMemento( int index )
{
return ledTvList.get(index);
}
}


Originator.java

/*
 * Hall
 */
public class Originator
{
LedTV ledTV;

public LedTV getLedTV()
{
return ledTV;
}

public void setLedTV( LedTV ledTV )
{
this.ledTV = ledTV;
}

public Memento createMemento()
{
return new Memento(ledTV);
}

public void setMemento( Memento memento )
{
ledTV = memento.getLedTV();
}

@Override
        public String toString()
        {
       return "Originator [ledTV=" + ledTV + "]";
        }

}

MementoClient.java

public class MementoClient
{

public static void main( String[] args )
{
Originator originator = new Originator();
originator.setLedTV(new LedTV("42 inch", "60000Rs", false));

Caretaker caretaker = new Caretaker();
caretaker.addMemento(originator.createMemento());

originator.setLedTV(new LedTV("46 inch", "80000Rs", true));
caretaker.addMemento(originator.createMemento());

originator.setLedTV(new LedTV("50 inch", "100000Rs", true));
System.out.println("\nOrignator current state : " + originator);

System.out.println("\nOriginator restoring to 42 inch LED TV...");

originator.setMemento(caretaker.getMemento(0));

System.out.println("\nOrignator current state : " + originator);

}

}

Output

LED TV's snapshots Maintained by CareTaker :[Memento [ledTV=LedTV [size=42 inch, price=60000Rs, usbSupport=false]]]
LED TV's snapshots Maintained by CareTaker :[Memento [ledTV=LedTV [size=42 inch, price=60000Rs, usbSupport=false]], Memento [ledTV=LedTV [size=46 inch, price=80000Rs, usbSupport=true]]]

Orignator current state : Originator [ledTV=LedTV [size=50 inch, price=100000Rs, usbSupport=true]]

Originator restoring to 42 inch LED TV...

Orignator current state : Originator [ledTV=LedTV [size=42 inch, price=60000Rs, usbSupport=false]]

See also:

  • Momento Design pattern - Introduction
  • Momento Design pattern - Real time Example
  • Memento Design pattern - Class Diagram
  • Memento Design pattern - Sequence Diagram
  • Momento Design pattern - KeyPoints
  • All Design Patterns Links
  • Wednesday, 13 November 2013

    Memento Design pattern - Sequence Diagram

    🚀 Master Java Design Patterns & Software Architecture!

    Subscribe to Ram N Java for clean software architecture patterns, design pattern deep dives, and production-ready implementation guides!

    🔔 Subscribe to Ram N Java

    Understanding the Memento Sequence Diagram

    The Memento Design Pattern is a behavioral pattern used to capture and restore the internal state of an object without exposing its internal structure. While class diagrams show the static relationships between the Originator, Memento, and Caretaker, a Sequence Diagram illustrates the dynamic runtime interactions, message exchanges, and exact chronological order required to save and restore state reliably.

    Runtime Sequence: Saving and Restoring State

    • Phase 1: Snapshot Creation: When an event triggers a checkpoint, the Caretaker requests the Originator to create a snapshot (e.g., via createMemento()).
    • Phase 2: Memento Instantiation: The Originator instantiates a new Memento object, passing its current private state fields into the memento constructor.
    • Phase 3: State Storage: The newly created memento is returned to the Caretaker, which safely holds or pushes it onto a history stack without inspecting its contents.
    • Phase 4: State Restoration (Undo): When an undo operation is requested, the Caretaker retrieves the memento from history and calls restore(memento) on the Originator, which rehydrates its internal fields.

    Key Roles Along the Interaction Lifeline

    1. Caretaker Lifeline: Initiates save and restore operations, managing checkpoint lifecycles while remaining completely ignorant of the state data inside the mementos.
    2. Originator Lifeline: Creates mementos reflecting its current internal state and accepts past mementos to restore previous configurations.
    3. Memento Lifeline: Represents the immutable snapshot object created dynamically during the save phase and passed back during the restore phase.

    Why Sequence Understanding Matters

    • Encapsulation Protection: The sequence demonstrates visually that the Caretaker never interacts directly with the private data of the Memento or Originator.
    • Clear Separation of Concerns: Shows the clean separation between history management (Caretaker) and actual business state tracking (Originator).
    • Predictable State Transitions: Clarifies the message flows required to build robust undo/redo stacks, transactional rollback checkpoints, and snapshot systems.

    Recommended Next Videos

    Continue your deep dive into the Memento pattern and behavioral design patterns with these related tutorials from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=mAGvR0XJOas

    Click the below Image to Enlarge

    Memento Design pattern - Sequence Diagram


















    See also:

  • Momento Design pattern - Introduction
  • Momento Design pattern - Real time Example
  • Memento Design pattern - Class Diagram
  • Memento Design pattern - Implementation
  • Momento Design pattern - KeyPoints
  • All Design Patterns Links
  • Memento Design pattern - Class Diagram

    🚀 Master Java Design Patterns & Software Architecture!

    Subscribe to Ram N Java for clean software architecture patterns, design pattern deep dives, and production-ready implementation guides!

    🔔 Subscribe to Ram N Java

    Understanding the Memento Design Pattern Class Diagram

    The Memento Design Pattern is a behavioral pattern that allows an application to capture and restore the internal state of an object without exposing its private implementation details. To implement this pattern cleanly in object-oriented systems, it is essential to master its structural architecture. A Unified Modeling Language (UML) class diagram provides a clear blueprint detailing how the Originator, Memento, and Caretaker classes interact while preserving encapsulation boundaries.

    Key Structural Components in UML

    • Originator: The primary business class containing mutable state. In the class diagram, it exposes methods such as createMemento() to produce state snapshots and restore(Memento) to restore past state.
    • Memento: The passive state container holding a snapshot of the Originator’s fields. It is modeled to have narrow visibility towards external components and wide access for the Originator.
    • Caretaker: The manager responsible for safe-keeping snapshots (e.g., maintaining an undo/redo stack or history collection). It never inspects, modifies, or accesses internal memento data.

    Relationships and Architectural Roles

    1. Dependency / Instantiation: The Originator instantiates and interacts with the Memento, populating it with snapshot data and consuming it during state restoration.
    2. Aggregation / Association: The Caretaker holds an aggregation reference (often a List<Memento> or Stack<Memento>) to preserve historical checkpoints over time.
    3. Encapsulation Shielding: The Caretaker interacts only with the Memento through a narrow interface (or treats it as an opaque token), ensuring private state attributes remain hidden.

    Architectural Advantages

    • Encapsulation Preservation: Eliminates the need for public getters and setters on sensitive internal state fields purely for persistence or undo purposes.
    • Single Responsibility Principle (SRP): Keeps history tracking, stack management, and storage lifecycles isolated in the Caretaker, leaving the Originator focused strictly on core business rules.
    • Modular & Extensible: Checkpoint storage strategies (e.g., file caching, memory stacks, or distributed persistence) can be modified without altering the Originator.

    Recommended Next Videos

    Continue your deep dive into the Memento pattern and behavioral design patterns with these related tutorials from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=O-VSseHwhcA

    Click the below Image to Enlarge
    Memento Design pattern - Class Diagram

















    See also:

  • Momento Design pattern - Introduction
  • Momento Design pattern - Real time Example
  • Memento Design pattern - Sequence Diagram
  • Memento Design pattern - Implementation
  • Momento Design pattern - KeyPoints
  • All Design Patterns Links
  • Saturday, 9 November 2013

    Memento Design pattern - Realtime Example

    🚀 Master Java Design Patterns & Software Architecture!

    Subscribe to Ram N Java for clean software architecture patterns, design pattern deep dives, and production-ready implementation guides!

    🔔 Subscribe to Ram N Java

    Real-World Application: Memento Pattern in Action

    Capturing and restoring state history is essential across various software systems—from document text editors and graphic design software to game checkpoints and multi-step transaction forms. The challenge lies in saving these snapshots without exposing an object's internal private fields. The Memento Design Pattern provides an elegant solution by encapsulating an object's state inside a dedicated snapshot without violating object-oriented encapsulation principles.

    Practical Demonstration & Workflow

    • State Changes: The user performs actions (such as typing text or modifying document properties), which update the internal state of the Originator.
    • Taking Checkpoints: Before executing high-impact modifications, the application triggers a save point. The Originator packages its active attributes into an immutable Memento.
    • Safe Storage: The Caretaker receives the Memento and pushes it onto an undo stack, keeping track of history without inspecting what is inside the checkpoint.
    • Rolling Back: When an undo operation is requested, the Caretaker pops the latest snapshot from its stack and passes it back to the Originator to restore its prior state effortlessly.

    Core Roles in the Demonstration

    1. Originator: Maintains the active business state (e.g., text content, configuration settings) and possesses full knowledge of how to create and restore from snapshots.
    2. Memento: Stores the snapshot data securely and immutably, ensuring external objects cannot tamper with the saved values.
    3. Caretaker: Coordinates save and rollback requests and manages the history timeline (e.g., stack or list of mementos).

    Architectural Advantages

    • Strict Encapsulation: Eliminates the bad practice of exposing private fields via public getters and setters solely for state persistence.
    • Simplified Business Logic: The Originator focuses purely on its domain tasks while delegating the history tracking lifecycle to the Caretaker.
    • Robust Undo/Redo Capabilities: Provides a predictable, decoupled foundation for implementing multi-level undo, rollback, and recovery workflows in enterprise applications.

    Recommended Next Videos

    Continue your deep dive into the Memento pattern and behavioral design patterns with these related tutorials from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=QA9K2XpcU2Q

    Click the below Image to Enlarge
    Memento Design pattern - Realtime Example

















    See also:

  • Momento Design pattern - Introduction
  • Memento Design pattern - Class Diagram
  • Memento Design pattern - Sequence Diagram
  • Memento Design pattern - Implementation
  • Momento Design pattern - KeyPoints
  • All Design Patterns Links
  • Memento Design pattern - Introduction

    🚀 Master Java Design Patterns & Software Architecture!

    Subscribe to Ram N Java for clean software architecture patterns, design pattern deep dives, and production-ready implementation guides!

    🔔 Subscribe to Ram N Java

    Introduction to the Memento Design Pattern

    In software development, managing state changes is a critical requirement across applications such as word processors, graphic design suites, game engines, and transactional workflows. Often, an application needs to roll back to a previous checkpoint. However, exposing an object’s private fields to an external history manager violates the fundamental principle of data encapsulation. The Memento Design Pattern addresses this problem by externalizing an object’s internal state into an opaque snapshot object, enabling rollback capabilities while keeping private implementation details hidden.

    Core Concepts & Architecture

    • Encapsulation-Safe State Capture: The pattern allows state capture without requiring public getters and setters for private fields.
    • Three Key Collaborators: Coordinates state lifecycle across three distinct entities: the Originator, the Memento, and the Caretaker.
    • Dual-Interface Protection: A classic memento pattern uses a wide interface for the Originator (allowing full access to state data) and a narrow interface for the Caretaker (preventing access to internal state data).
    • Transactional Safety: Facilitates undo/redo operations and recovery checkpoints in long-running processes.

    Primary Pattern Participants

    1. Originator: The business object that possesses an internal state. It is responsible for creating a Memento holding a snapshot of its state and using past Mementos to restore itself.
    2. Memento: An immutable object that encapsulates the state snapshot of the Originator. It restricts direct access from external classes to safeguard encapsulation.
    3. Caretaker: The manager responsible for storing and tracking snapshots (e.g., maintaining an undo stack). It never inspects or mutates the internal contents of the mementos.

    Architectural Advantages

    • Preserves Information Hiding: Keeps the Originator's private implementation encapsulated, avoiding code smell like exposing private state via getters.
    • Decouples Lifecycle and Storage: The Originator does not need to handle history management, arrays, or stacks—the Caretaker handles storage lifecycles independently.
    • Predictable State Rollbacks: Provides a standardized, clean foundation for multi-level undo, rollback mechanisms, and system checkpoint recovery.

    Recommended Next Videos

    Continue your deep dive into the Memento pattern and behavioral design patterns with these related tutorials from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=QPhSMIBfMjA

    Click the below Image to Enlarge
    Memento Design pattern - Introduction

















    See also:

  • Momento Design pattern - Real time Example
  • Memento Design pattern - Class Diagram
  • Memento Design pattern - Sequence Diagram
  • Memento Design pattern - Implementation
  • Momento Design pattern - KeyPoints
  • All Design Patterns Links
  • Thursday, 7 November 2013

    Memento Design pattern - KeyPoints

    🚀 Master Java Design Patterns & Software Architecture!

    Subscribe to Ram N Java for clean software architecture patterns, design pattern deep dives, and production-ready implementation guides!

    🔔 Subscribe to Ram N Java

    Key Takeaways: Memento Design Pattern

    The Memento Design Pattern is a foundational Gang of Four (GoF) behavioral pattern engineered to capture and externalize an object’s internal state so that it can be restored later without violating encapsulation. Understanding the core takeaways, essential rules, and trade-offs of this pattern enables software engineers to implement clean undo/redo mechanisms, transaction rollbacks, and recovery checkpoints in enterprise systems.

    Core Concepts & Architecture

    • Encapsulation Integrity: The primary objective of the Memento pattern is safeguarding encapsulation boundaries. State details remain private to the Originator and completely opaque to the Caretaker.
    • Distinct Separation of Roles: The pattern relies on three distinct collaborators: the Originator (state owner), the Memento (state snapshot), and the Caretaker (state manager).
    • Wide vs. Narrow Interface: A standard memento architecture presents two interfaces: a wide interface accessible only to the Originator (allowing full state extraction/restoration) and a narrow interface to the Caretaker (preventing inspection or mutation of state fields).
    • Immutability of Snapshots: Once a Memento is created, its captured state should never be modified.

    When Should You Apply the Memento Pattern?

    1. Undo and Redo Functionality: When building interactive user interfaces, text editors, canvas applications, or graphic editors that require multi-level rollbacks.
    2. Transactional Integrity & Rollback: When an operation may fail midway and requires rolling back to a known stable snapshot without re-instantiating the entire object.
    3. Checkpoint and State Persistence: When saving game progress, multi-step wizard form sessions, or system configuration recovery points.

    Advantages & Trade-Offs

    • Zero Exposure of Private Data: Eliminates antipatterns like exposing internal fields via public getters and setters solely for snapshotting.
    • Simplified Originator Code: Offloads checkpoint storage, history management, and stack tracking entirely to the Caretaker.
    • Memory Footprint Consideration: Storing numerous full-state snapshots can consume substantial memory. For high-volume states, consider delta-based storage or limiting history capacity.

    Recommended Next Videos

    Continue your deep dive into the Memento pattern and behavioral design patterns with these related tutorials from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=72U7hbxHCUw

    Click the below Image to Enlarge


















    See also:

  • Momento Design pattern - Introduction
  • Momento Design pattern - Real time Example
  • Memento Design pattern - Class Diagram
  • Memento Design pattern - Sequence Diagram
  • Memento Design pattern - Implementation
  • All Design Patterns Links
  • Tutorials