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(

Azure AD and AWS Cognito side-by-side

In the last few weeks, I was involved in multiple opportunities on Microsoft Azure and Amazon, where we had to analyse AWS Cognito, Azure AD and other solutions that are available on the market. I decided to consolidate in one post all features and differences that I identified for both of them that we should need to take into account. Take into account that Azure AD is an identity and access management services well integrated with Microsoft stack. In comparison, AWS Cognito is just a user sign-up, sign-in and access control and nothing more. The focus is not on the main features, is more on small things that can make a difference when you want to decide where we want to store and manage our users.  This information might be useful in the future when we need to decide where we want to keep and manage our users.  Feature Azure AD (B2C, B2C) AWS Cognito Access token lifetime Default 1h – the value is configurable 1h – cannot be modified

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