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

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

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.51EF 6.0.2VS2013
It seems that there …

Run native .NET application in Docker (.NET Framework 4.6.2)

Scope
The main scope of this post is to see how we can run a legacy application written in .NET Framework in Docker.

Context
First of all, let’s define what is a legacy application in our context. By a legacy application we understand an application that runs .NET Framework 3.5 or higher in a production environment where we don’t have any more the people or documentation that would help us to understand what is happening behind the scene.
In this scenarios, you might want to migrate the current solution from a standard environment to Docker. There are many advantages for such a migration, like:

Continuous DeploymentTestingIsolationSecurity at container levelVersioning ControlEnvironment Standardization
Until now, we didn’t had the possibility to run a .NET application in Docker. With .NET Core, there was support for .NET Core in Docker, but migration from a full .NET framework to .NET Core can be costly and even impossible. Not only because of lack of features, but also because once you…