Memento
pattern is not very popular design pattern but sometimes it perform heroic task
to solve business problem. Sometime situation come like that- We can allow user
to put his input and even after putting new input they want to revert back
there previous value.
Say for
example:- In online quiz user can give answer three time. At first user might
give wrong answer ,then again wrong and in third time after giving answer
before pressing confirm button she want to revert back the previous answer.
This kind
of problem can able to solve by Memento design pattern.
So, What
is the mechanism? How it’s happening ? very simple .
We will
create a memento class which will be exact mirror of original class. And when we will create object of original
class that time same copy of that object we will create by memento class and
will keep separately. Talking too much..Let’s look below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;
namespace BlogProject
{
//Momento Desing pattern
class OriginalObject
{
public string Name { get; set; }
public string Surname
{ get; set; }
public Momento
SetMomento { get; set;
}
public OriginalObject(string
Name, String Surname)
{
this.Name = Name;
this.Surname = Surname;
this.SetMomento = new
Momento(Name, Surname);
}
public void
ChangeData()
{
this.Name = "New
Name";
this.Surname = "New
Surname";
}
public void Revert()
{
Console.WriteLine(SetMomento.Name +
SetMomento.Surname);
}
}
class Momento
{
public string Name { get; set; }
public string Surname
{ get; set; }
public Momento(string
Name, String Surname)
{
this.Name = Name;
this.Surname = Surname;
}
}
class Program
{
static void Main(string[] args)
{
OriginalObject obj = new
OriginalObject("Sourav",
"Kayal");
obj.ChangeData();
obj.Revert();
Console.ReadLine();
}
}
}
No comments:
Post a Comment