Implementation of Memento Pattern in C#

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 1424
What is Memento Pattern?
Sometimes we want to perform undo with the changes. In such case situations memento helps.

Let’s look below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Diagnostics;

namespace TestMemento
{

class OriginalObject
{
public string Name { get; set; }
public Momento SetMomento { get; set; }

public OriginalObject(string Name)
{
this.Name = Name;
this.SetMomento = new Momento(Name);
}

public void ChangeData()
{
this.Name = "Changed Name";
Console.WriteLine(SetMomento.Name);
}

public void Revert()
{
Console.WriteLine(SetMomento.Name);
}
}

class Momento
{
public string Name { get; set; }
public Momento(string Name)
{
this.Name = Name;
}
}


class Program
{
static void Main(string[] args)
{
OriginalObject obj = new OriginalObject("This is original name");
obj.ChangeData();
obj.Revert();
Console.ReadLine();
}
}
}


In this case the Momento class plays the vital role.It stores the original value and when the ChangeData() is called then the new value is printed. Again when the Revert() is called, then it picks up the value from SetMomento.Name property and the original value retains.

Comments or Responses

Login to post response