Friday, September 13, 2024

Memento Design Pattern in C#

The Memento Design Pattern is a Behavioral Design Pattern that can restore an object to its previous state. This pattern is useful for scenarios where you need to perform an undo or rollback operation in your application. The Memento pattern captures an object’s internal state so that the object can be restored to this state later. It is especially useful when implementing undo functionality in an application.

Component of Memento Design Pattern

  1. Originator: The object whose state you want to save or restore.
  2. Memento: Stores the internal state of the Originator. It has two interfaces:
    • Caretaker Interface: This interface provides no access to the internal state of the Memento. It is used by the Caretaker to manage the Memento without modifying it.
    • Originator Interface: This interface allows the Originator to access the Memento to restore its state.
  3. Caretaker: The object that requests the saving and restoring of the Originator’s state.

Implementing Memento Pattern in C#

Define the Memento
namespace MementoPattern
{
    /// <summary>
    /// Memento class to hold the state
    /// </summary>
    public class Memento
    {
        public string State { get; private set; }

        public Memento(string state)
        {
            State = state;
        }
    }
}
Implement the Originator
namespace MementoPattern
{
    /// <summary>
    /// Originator class that uses Memento to save and restore state
    /// </summary>
    public class Originator
    {
        public string State { get; set; }

        public void SetState(string state)
        {
            Console.WriteLine($"Setting state to: {state}");
            State = state;
        }

        public Memento SaveStateToMemento()
        {
            Console.WriteLine("Saving state to Memento.");
            return new Memento(State);
        }

        public void RestoreStateFromMemento(Memento memento)
        {
            State = memento.State;
            Console.WriteLine($"Restored state from Memento: {State}");
        }
    }
}
Create the Caretaker
namespace MementoPattern
{
    /// <summary>
    /// Caretaker class that manages Mementos
    /// </summary>
    public class Caretaker
    {
        private List<Memento> _mementoList = new List<Memento>();

        public void AddMemento(Memento memento)
        {
            _mementoList.Add(memento);
            Console.WriteLine("State saved to Caretaker.");
        }

        public Memento GetMemento(int index)
        {
            return _mementoList[index];
        }
    }
}
Test the Memento Pattern(Program.cs)
// Create Originator and Caretaker objects
using MementoPattern;

Originator originator = new Originator();
Caretaker caretaker = new Caretaker();

// Set and save some states
originator.SetState("State 1");
caretaker.AddMemento(originator.SaveStateToMemento());

originator.SetState("State 2");
caretaker.AddMemento(originator.SaveStateToMemento());

originator.SetState("State 3");
caretaker.AddMemento(originator.SaveStateToMemento());

// Restore previous states
Console.WriteLine("\nRestoring states:");
originator.RestoreStateFromMemento(caretaker.GetMemento(0));
originator.RestoreStateFromMemento(caretaker.GetMemento(1));
Console.ReadLine();

Explanation

  1. The Originator class represents the object whose state needs to be saved and restored. It has a SetState method for changing the state and a SaveStateToMemento method for saving the current state to a Memento.
  2. The Memento class stores the state of the Originator.
  3. The Caretaker class is responsible for keeping a collection of Memento objects. It doesn’t modify or access the internal state of the Memento, but it can store and retrieve them.

Output

Memento Design Pattern in C#

Key Takeaway

  • The Memento pattern is useful for implementing undo/redo functionality by saving different states of an object at different points in time.
  • The Caretaker stores Memento objects without needing to understand their contents.
  • The Originator can use a Memento to restore its state at any given point.

This pattern helps to manage the internal state of complex objects in a clean and effective manner without exposing internal details to other classes.

Memento Design Pattern

Happy coding!! 😊

No comments:

Post a Comment

^ Scroll to Top