# Memento

> Snapshot an object's state and store it externally so you can restore it later — without breaking encapsulation or exposing internals.

- **Category**: Software Design
- **Subcategory**: behavioral
- **Canonical URL**: https://designpattern.fyi/patterns/memento/

---

## Description
**Intent**: Save and restore object state for undo/redo, checkpointing, or state rollback without leaking private implementation details.

**Context**: You're building a text editor, drawing app, game with save states, or any system where users can undo actions. The object holding the state shouldn't expose its internals just to support snapshotting.

**Solution**: The Originator (object being saved) creates a Memento — an opaque snapshot of its private state. A Caretaker stores and manages Mementos without being able to read them. When rollback is needed, the Originator restores from a Memento.


## Use Cases
Use for undo/redo stacks, game save states, transaction rollbacks, or any scenario where you need point-in-time snapshots of an object's state.



## Implementation Example

```javascript
class Memento {
  constructor(state) { this.state = state; }
  getState() { return this.state; }
}

class Originator {
  constructor(state) { this.state = state; }
  save() { return new Memento(this.state); }
  restore(memento) { this.state = memento.getState(); }
}

```



## Trade-offs


### Advantages

- Snapshots are stored externally without violating the object's encapsulation.

- Originator code stays clean — the Caretaker owns the history management.




### Considerations & Drawbacks

- Can devour RAM fast if mementos are created frequently or if the state is large.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/memento)

