# Memento Pattern in Java: Techniques for Managing State Without Breaking Encapsulation

<div><strong>Source</strong>: <a href='https://www.tuanh.net/blog/java/memento-pattern-in-java-techniques-for-managing-state-without-breaking-encapsulation'>Memento Pattern in Java: Techniques for Managing State Without Breaking Encapsulation</a></div><div class="line-post"> 
 <h2 class="title-post">1. What is the Memento Pattern?</h2> 
</div>
<div class="line-post">
  The Memento Pattern is one of the behavioral design patterns that focus on how objects interact. It’s designed to store and restore an object’s state without compromising encapsulation. The pattern is particularly useful in applications that require state management across various operations. 
</div>
<div class="line-post">
  The Memento Pattern provides a way to save an object’s state to restore it later. The key advantage of this pattern is that it keeps the object's internal details hidden from the outside world. This encapsulation is vital for maintaining code safety and integrity. 
</div>
<div class="line-post">
  Imagine a text editor with an undo feature. Every time a user types or deletes text, the editor creates a snapshot of the content. When the user presses "undo," the editor retrieves the last saved state. This is the essence of the Memento Pattern. 
</div>
<div class="line-post">
  Components of the Memento Pattern: 
</div>
<div class="line-post"> 
 <ul> 
  <li><strong>Originator</strong>: The object that holds the current state.</li> 
  <li><strong>Memento</strong>: The snapshot that stores the state.</li> 
  <li><strong>Caretaker</strong>: Manages mementos, enabling the Originator to revert to previous states.</li> 
 </ul> 
</div>
<div class="line-post">
  Here’s a simple example where we use the Memento Pattern to manage the state of a text editor. This example will illustrate the three main components in action. 
</div>
<pre class="code"><span class="keyword-css">public</span> <span class="keyword-css">class</span> TextEditor {<br>    <span class="keyword-css">private</span> String content;<br><br>    <span class="keyword-css">public</span> <span class="keyword-css">void</span> setContent(String content) {<br>        <span class="keyword-css">this</span>.content = content;<br>    }<br><br>    <span class="keyword-css">public</span> String getContent() {<br>        <span class="keyword-css">return</span> content;<br>    }<br><br>    <span class="keyword-css">public</span> Memento save() {<br>        <span class="keyword-css">return</span> <span class="keyword-css">new</span> Memento(content);<br>    }<br><br>    <span class="keyword-css">public</span> <span class="keyword-css">void</span> restore(Memento memento) {<br>        <span class="keyword-css">this</span>.content = memento.getContent();<br>    }<br><br>    <span class="keyword-css">public</span> <span class="keyword-css">static</span> <span class="keyword-css">class</span> Memento {<br>        <span class="keyword-css">private</span> <span class="keyword-css">final</span> String content;<br><br>        <span class="keyword-css">private</span> Memento(String content) {<br>            <span class="keyword-css">this</span>.content = content;<br>        }<br><br>        <span class="keyword-css">private</span> String getContent() {<br>            <span class="keyword-css">return</span> content;<br>        }<br>    }<br>}</pre>
<div class="line-post"> 
 <h2 class="title-post">2. Implementing the Memento Pattern in Java</h2> 
</div>
<div class="line-post">
  In this section, let’s build a more complex version of the Memento Pattern and add a Caretaker class. The Caretaker will manage saved states and allow the Originator to revert as necessary. 
</div>
<div class="line-post">
  The Caretaker class holds a list of mementos. For example, in a text editor, it allows the user to undo and redo multiple steps. Here’s how we implement this in Java. 
</div>
<pre class="code"><span class="keyword-css">import</span> java.util.Stack;<br><br><span class="keyword-css">public</span> <span class="keyword-css">class</span> History {<br>    <span class="keyword-css">private</span> <span class="keyword-css">final</span> Stack&lt;TextEditor.Memento&gt; history = <span class="keyword-css">new</span> Stack&lt;&gt;();<br><br>    <span class="keyword-css">public</span> <span class="keyword-css">void</span> save(TextEditor editor) {<br>        history.push(editor.save());<br>    }<br><br>    <span class="keyword-css">public</span> <span class="keyword-css">void</span> undo(TextEditor editor) {<br>        <span class="keyword-css">if</span> (!history.isEmpty()) {<br>            editor.restore(history.pop());<br>        }<br>    }<br>}</pre>
<div class="line-post">
  Here’s how you would use the TextEditor and History classes to enable undo functionality in an application: 
</div>
<pre class="code"><span class="keyword-css">public</span> <span class="keyword-css">class</span> Main {<br>    <span class="keyword-css">public</span> <span class="keyword-css">static</span> <span class="keyword-css">void</span> main(String[] args) {<br>        TextEditor editor = <span class="keyword-css">new</span> TextEditor();<br>        History history = <span class="keyword-css">new</span> History();<br><br>        editor.setContent("Version 1");<br>        history.save(editor);<br>        <br>        editor.setContent("Version 2");<br>        history.save(editor);<br>        <br>        editor.setContent("Version 3");<br>        System.out.println("Current Content: " + editor.getContent());<br><br>        history.undo(editor);<br>        System.out.println("After undo: " + editor.getContent());<br><br>        history.undo(editor);<br>        System.out.println("After second undo: " + editor.getContent());<br>    }<br>}</pre>
<div class="line-post">
  Output: 
</div>
<pre class="code">Current Content: Version 3<br>After undo: Version 2<br>After second undo: Version 1</pre>
<div class="line-post"> 
 <h2 class="title-post">3. Best Practices for Using the Memento Pattern</h2> 
</div>
<div class="line-post"> <strong>Maintain Encapsulation</strong> 
</div>
<div class="line-post">
  Use private or inner classes to prevent external access to the Memento. This ensures the internal state remains hidden from other objects. 
</div>
<div class="line-post"> <strong>Manage Memory Effectively</strong> 
</div>
<div class="line-post">
  Saving too many states can lead to memory issues. Consider setting limits on the number of saved Mementos or using a lightweight data structure. 
</div>
<div class="line-post"> <strong>Optimize for Performance</strong> 
</div>
<div class="line-post">
  If your application requires frequent state saving, you might need to look into optimized data structures or consider saving differential states instead of full snapshots. 
</div>
<div class="line-post"> 
 <h2 class="title-post">4. Challenges and Limitations of the Memento Pattern</h2> 
</div>
<div class="line-post"> <strong>Memory Overhead</strong> 
</div>
<div class="line-post">
  Each Memento represents a complete state of the Originator. In memory-intensive applications, storing many Mementos may not be practical. Strategies such as saving only when significant changes occur can help manage memory more efficiently. 
</div>
<div class="line-post"> <strong>Compatibility with Multithreading</strong> 
</div>
<div class="line-post">
  If the Originator is part of a multithreaded application, synchronizing access to the Memento objects is necessary to avoid race conditions. 
</div>
<div class="line-post"> <strong>Complexity in Serialization</strong> 
</div>
<div class="line-post">
  When working with objects that need to be serialized, the Memento Pattern can add overhead. Java provides tools like Serializable, but serialization can be time-consuming and may introduce additional complexities. 
</div>
<div class="line-post"> 
 <h2 class="title-post">5. Conclusion</h2> 
</div>
<div class="line-post">
  The Memento Pattern provides a powerful way to manage and revert object states, making it an excellent choice for applications requiring undo/redo functionality or state history tracking. However, it’s essential to carefully consider memory and performance impacts. Using best practices for encapsulation, memory management, and compatibility with multithreaded applications will help you maximize the benefits of this pattern. If you have any questions or experiences to share about implementing the Memento Pattern, feel free to comment below! 
</div><p><strong>Read more at </strong>: <a href='https://www.tuanh.net/blog/java/memento-pattern-in-java-techniques-for-managing-state-without-breaking-encapsulation'>Memento Pattern in Java: Techniques for Managing State Without Breaking Encapsulation</a></p>
