Skip to main content

Memento Pattern - the key to unde/redo functionality

Cati dintre voi ati auzit de paternul Memento? Astazi vrea sa povestim despre acest patern.
Ca si multe alte paternuri, acesta il folosim de foarte multe ori fara sa ne dam seama. In viata de zi cu zi, de fiecare data cand dam Undo/Redo in Visual Studio sau in Word o forma a acestui patern este folosita.
Acest patern ne ofera posibilitatea sa readucem obiectul intr-o stare precedenta. Aceasta stare a fost de catre noi salvata intr-un anumit moment si putem sa revenim la ea in orice moment. In momentul in la un obiect se face rollback spre o stare din trecut, acesta o sa aibe aceiasi stare ca si in momentul respectiv.
Atentie, starea unui obiect intr-un anumit moment este o notiune abstracta, care in functie de caz si de ce este nevoie pentru un anumit caz. Din aceasta cauza o salvare de stare poate sa implice ca doar o parte din valorile unui obiect sa reprezinta o anumita stare.
In momentul cand vrem sa implementam acest patern, o sa avem trei entitati implicate in aceasta poveste.
  • Originator - acest obiect reprezinta obiectul la care noi salvam statie si stie sa se salveze pe el insusi
  • Memento - este obiectul unde se salveaza Originator-ul in stare data. Toate valorile care apartin de Originator in stare in care s-a facut salvarea sunt stocare in acest obiect
  • Caretaker - este cel care stie de ce si cand Origininator trebuie sa salveze sau sa isi faca restore
Am vazut diferite implementari la acest patern, dar o raman pe cea mai simpla.
Mai jos gasiti un exemplu de implementare:
public class Memento
{
public string State { get; private set; }

public Memento(string state)
{
State = state;
}
}

public class Original
{
public string State { get; set; }

public Memento CreateMemento()
{
return new Memento(State);
}

public void RestoreMemento(Memento memento)
{
State = memento.State;
}
}

public class Caretaker
{
public Memento Memento { get; set; }
}

Iar utilizarea s-a este urmatoarea:
static void Main(string[] args)
{
Original original = new Original()
{
State = "1"
};
Console.WriteLine(original.State);

Caretaker caretaker = new Caretaker();
caretaker.Memento = original.CreateMemento();
original.State = "2";
Console.WriteLine(original.State);

original.RestoreMemento(caretaker.Memento);
Console.WriteLine(original.State);
}
Sa nu uitati cand salvati obiectele (la cele de tip referinte), sa o faceti printr-o cloanare (sub orice forma ar fi aceasta) si doar prin referinta. Deoarece in cazul in care se face restore la un obiect o sa aveti parte de surprize. O solutie la aceasta probleme este sa implementati interfata IClonable pentru Originator. Dar trebuie sa aveti grija ca acest lucru este cu doua taisuri. Recomand totusi o metoda separata pentru partea de salvare a unei stari curente.
Daca avem putina imaginatie, putem sa ne implementam un mecanism de undo/redo destul de usor. Am putea sa folosim doua cozi de mesaje, una care sa tina toate starile pentru undo si alta pentru redo. Trebuie sa aveti grija, cand luati un Memento de pe o anumita coada sa il puneti imediat pe cealalta si cand adaugi un nou memento sa resetati coada de redo.
Mai jos puteti sa gasiti o implementare. M-am aberat de dragul artei putin.
public enum MementoType
{
Undo,
Redo
}

public interface IMemento<T>
where T : IOriginator
{
}

public class Memento<T> : IMemento<T>
where T : IOriginator
{
public T State { get; private set; }

public Memento(T originator)
{
State = (T)originator.Clone();
}
}

public interface IOriginator : ICloneable
{
IMemento<IOriginator> CreateMemento();

void RestoreMemento(IMemento<IOriginator> memento);
}

public abstract class Originator : IOriginator
{
public abstract object Clone();

public abstract void RestoreMemento(IMemento<IOriginator> memento);

public IMemento<IOriginator> CreateMemento()
{
return new Memento<IOriginator>(this);
}
}

public interface ICaretaker
{
void AddMemento<TOriginator>(TOriginator originator)
where TOriginator : IOriginator;

TOriginator GetMemento<TOriginator>(MementoType type)
where TOriginator : IOriginator;
}

public class Caretaker : ICaretaker
{
public IDictionary<Type, Stack<IOriginator>> _redoItems = new Dictionary<Type, Stack<IOriginator>>();
public IDictionary<Type, Stack<IOriginator>> _undoItems = new Dictionary<Type, Stack<IOriginator>>();

public void AddMemento<TOriginator>(TOriginator originator)
where TOriginator : IOriginator
{
Stack<IOriginator> currentStack = GetStack<TOriginator>(MementoType.Undo);
GetStack<TOriginator>(MementoType.Redo).Clear();
currentStack.Push(originator);
}

public TOriginator GetMemento<TOriginator>(MementoType type)
where TOriginator : IOriginator
{
Stack<IOriginator> currentStack = GetStack<TOriginator>(type);

if (currentStack.Count==0)
{
throw new KeyNotFoundException(
string.Format("The memento was not found in the dictionary, {0}", typeof(TOriginator).FullName));
}

IOriginator current = currentStack.Pop();
GetOppositeStack<TOriginator>(type).Push(current);

return (TOriginator)current;
}

private Stack<IOriginator> GetStack<TOriginator>(MementoType type)
where TOriginator : IOriginator
{
IDictionary<Type, Stack<IOriginator>> currentMapping = GetMapping(type);

return GetStack(currentMapping, typeof(TOriginator));
}

private IDictionary<Type, Stack<IOriginator>> GetMapping(MementoType type)
{
IDictionary<Type, Stack<IOriginator>> currentMapping = null;
switch (type)
{
case MementoType.Undo:
currentMapping = _undoItems;
break;
case MementoType.Redo:
currentMapping = _redoItems;
break;
}

return currentMapping;
}

private Stack<IOriginator> GetOppositeStack<TOriginator>(MementoType type)
where TOriginator : IOriginator
{
return GetStack(GetMapping(GetOppositeType(type)), typeof(TOriginator));
}

private MementoType GetOppositeType(MementoType type)
{
MementoType oppositeType;
switch (type)
{
case MementoType.Undo:
oppositeType = MementoType.Redo;
break;
case MementoType.Redo:
oppositeType = MementoType.Undo;
break;
default:
throw new NotImplementedException();
}

return oppositeType;
}

private Stack<IOriginator> GetStack(IDictionary<Type, Stack<IOriginator>> mapping, Type mementoType)
{
Stack<IOriginator> currentStack = null;
if (mapping.ContainsKey(mementoType))
{
currentStack = mapping[mementoType];
}
else
{
currentStack = new Stack<IOriginator>();
mapping.Add(mementoType, currentStack);
}

return currentStack;
}
}
Acuma ca am vazut paternul de baza, ne putem da seama ca exista multe variante. In unele implementari obiectul Originator nu stie sa isi salveze starea, iar o alta entitate se ocupa cu acest lucru. In alte cazuri, Caretaker-ul lipseste in totalitate.
As vrea sa va atrag atentia la cel mai important lucru cred. Mement-ul reprezinta starea unui obiect dintr-un anumit moment si pe baza lui trebuie sa puteti reveni la starea data indiferent de context.

Comments

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine: threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration: TeamCity .NET 4.51 EF 6.0.2 VS2013 It see

Navigating Cloud Strategy after Azure Central US Region Outage

 Looking back, July 19, 2024, was challenging for customers using Microsoft Azure or Windows machines. Two major outages affected customers using CrowdStrike Falcon or Microsoft Azure computation resources in the Central US. These two outages affected many people and put many businesses on pause for a few hours or even days. The overlap of these two issues was a nightmare for travellers. In addition to blue screens in the airport terminals, they could not get additional information from the airport website, airline personnel, or the support line because they were affected by the outage in the Central US region or the CrowdStrike outage.   But what happened in reality? A faulty CrowdStrike update affected Windows computers globally, from airports and healthcare to small businesses, affecting over 8.5m computers. Even if the Falson Sensor software defect was identified and a fix deployed shortly after, the recovery took longer. In parallel with CrowdStrike, Microsoft provided a too