Windows Mobile Support

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Wednesday, 27 June 2012

Memento Pattern - the key to unde/redo functionality

Posted on 16:29 by Unknown
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.
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in design patterns | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Service Bus Topic - Automatic forward messages from a subscription to a topic
    Windows Azure Service Bus Topic is a service that enables us to distribute the same messages to different consumers without having to know e...
  • CDN is not the only solution to improve the page speed - Reverse Caching Proxy
    I heard more and more often think like this: “If your website is to slow, you should use a CDN.” Great, CDN is THE solution for any kind of ...
  • Content Types - Level 6: Rich Media
    Level 6: Rich Media NOTE: This is part 7 of 7 and the conclusion of this continuing series; please see earlier posts for more background inf...
  • Publishing our CellCast Widget for iPad
    The rush has been on this week as our development team worked to design a new version of our CellCast Widget specifically for Apple's up...
  • Patterns in Windows Azure Service Bus - Message Splitter Pattern
    In one of my post about Service Bus Topics from Windows Azure I told you that I will write about a post that describe how we can design an a...
  • E-Learning Vendors Attempt to Morph Mobile
    The sign should read: " Don't touch! Wet Paint !" I had a good chuckle today after receiving my latest emailed copy of the eLe...
  • SQL - UNION and UNION ALL
    I think that all of us used until now UNION in a SQLstatement. Using this operator we can combine the result of 2 queries. For example we wa...
  • Cum sa salvezi un stream direct intr-un fisier
    Cred ca este a 2-a oara când întâlnesc aceasta cerința in decurs de câteva săptămâni. Se da un stream și o locație unde trebuie salvat, se c...
  • Task.Yield(...), Task.Delay(...)
    I think that a lot of person already heard about these new methods. In this post I want to clarify some things about these new methods that ...
  • Content Types - Level 4: Reference
    Level 4: Reference Materials & Static Content NOTE: This is part 5 of 7 in a continuing series; please see earlier posts for more backgr...

Categories

  • .NET
  • .NET nice to have
  • #if DEBUG
  • 15 iunie 2011
  • 15 octombrie 2011
  • 2011
  • abstracta
  • action
  • adaugare
  • ajax
  • Amsterdam
  • Android
  • aplicatii
  • App Fabric
  • Apple iSlate
  • array
  • as
  • ASP.NET
  • AsReadOnly
  • Assembly comun
  • async
  • Asynchronous programming
  • asyncron
  • Autofac
  • AutoMapper
  • az
  • Azure
  • Azure AppFabric Cache
  • Azure backup solution
  • Azure Storage Explorer
  • azure. cloud
  • backup
  • BCP utility
  • bing maps v7
  • BitArray
  • BlackBerry
  • blob
  • BlobContainerPublicAccessType
  • breakpoint
  • bucuresti
  • C#
  • cache
  • CallerMemberName
  • CellCast
  • Certificate
  • CES
  • change
  • ChannelFactory
  • clasa
  • classinitialize
  • clean code
  • click event
  • close
  • Cloud
  • Cluj
  • cluj-napoca
  • Code contracts
  • code retrat
  • codecamp
  • CollectionAssert
  • Compact Edition
  • compara
  • Comparer T .Default
  • CompareTo
  • comparison
  • comunitate
  • concurs
  • Conditional attribute
  • configurare
  • connection string
  • container
  • content type
  • control
  • Convert
  • convertAll
  • convertor
  • cross platform
  • CRUD
  • css
  • custom properties
  • custom request
  • DACPAC
  • Daniel Andres
  • data sync service
  • database
  • date time
  • datetime
  • debug
  • default
  • delegate
  • dependency injection
  • deploy
  • DeploymentItem
  • design patterns
  • Dev de Amsterdam
  • development stoage
  • dictionary
  • diferente
  • digging
  • director
  • Directory.Exist
  • disable
  • dispatcher
  • dispose
  • dropdown
  • dynamic
  • EF
  • email
  • encoding
  • entity framework
  • enum
  • enumerable
  • Environment.NewLine
  • error
  • error 404
  • error handling
  • eveniment
  • event
  • ews
  • excel
  • exception
  • exchange
  • exita
  • explicit
  • export
  • extension
  • field
  • File.Exist
  • finalize
  • fire and forget
  • Fluent interface pattern
  • format
  • func
  • GC.SuppressFinalize
  • generic
  • getdirectoryname
  • globalization
  • gmail
  • hackathon
  • Hadoop
  • handle
  • HTML
  • html 5
  • Html.ActionLink
  • http://www.blogger.com/img/blank.gif
  • HttpModule
  • IComparable
  • IE
  • ienumerable
  • IIS
  • image
  • implicit
  • import
  • int
  • internationalization
  • Internet Explorer
  • interop
  • Ioc
  • IP Filter
  • iPhone
  • iQuest
  • IStructuralEquatable
  • ITCamp
  • itspark
  • java script
  • javascript
  • July 2012
  • KeyedByTypeCollection
  • KeyNotFoundException
  • Kinect SDK
  • lambda expression
  • LightSwitch Microsoft Silverlight
  • linq
  • list
  • lista
  • lista servicii
  • liste
  • Live Connect
  • Live ID
  • load
  • localization
  • lock
  • m-learning
  • MAC
  • Mango
  • map
  • mapare
  • mapare propietati
  • messagequeue
  • meta properties
  • method
  • MethodImpl
  • Metro App
  • Microsoft
  • Microsoft Sync Framework
  • mlearning
  • mlearning devices
  • Mobile Apps
  • mobile in the cloud
  • mobile learning
  • mobile services
  • Mobile Web
  • mongoDb
  • monitorizare
  • msmq
  • multitasking
  • MVC
  • MVC 3
  • MVVM
  • namespace
  • nextpartitionkey
  • nextrowkey
  • Ninject
  • nivel acces
  • no result
  • normalize
  • nosql
  • null expcetion
  • null object pattern
  • NullReferenceException
  • OAuth API
  • office
  • offline
  • Open ID
  • openhackeu2011
  • operations
  • operator
  • optimization
  • option
  • outputcache
  • OutputCacheProvider
  • override
  • paginare
  • pagination
  • path
  • persistare
  • Portable Library tool
  • Post event – CodeCamp Cluj-Napoca
  • predicate
  • predictions
  • prezentare
  • process
  • proiect
  • property
  • propietati
  • query
  • ReadOnlyCollection
  • ReadOnlyDictionary
  • referinta
  • reflection
  • remote
  • reply command
  • request
  • request response
  • resouce
  • REST
  • REST Client
  • RESTSharp
  • ronua
  • rss
  • rulare
  • salvare in fisier
  • sc
  • schimbare timp
  • select
  • select nodes
  • send
  • serializare
  • serialization
  • Server.Transfer. Resposen.Redirect
  • service bus
  • ServiceBase
  • servicecontroller
  • sesiune
  • session
  • Session_End
  • Session_Start
  • setup
  • Sibiu
  • signalR
  • Silverlight
  • sincronizare
  • Single Responsibility Principle
  • SkyDrive
  • skype
  • smartphones
  • smtp
  • Snapguide
  • sniffer
  • socket
  • solid
  • spec#
  • sql
  • Sql Azure
  • SQL CE
  • sql server 2008 RC
  • SRP
  • startuptype
  • stateful
  • stateless
  • static
  • stergere
  • store
  • store procedure
  • stream
  • string
  • string.join
  • struct
  • StructuralEqualityComparer
  • submit
  • switch
  • Symbian
  • Synchronized
  • system
  • tabele
  • table
  • techEd 2012
  • tempdata
  • test
  • testcleanup
  • testinitialize
  • testmethod
  • thread
  • timer
  • ToLower
  • tool
  • tostring
  • Total Cost Calculator
  • trace ASP.NET
  • transcoding
  • tuplu
  • tutorial
  • TWmLearning
  • type
  • unit test
  • unittest
  • UrlParameter.Optional
  • Validate
  • validation
  • verificare
  • video
  • view
  • ViewBag
  • virtual
  • visual studio
  • VM role
  • Vunvulea Radu
  • wallpaper
  • WCF
  • WebBrower
  • WebRequest
  • where clause
  • Windows
  • windows 8
  • Windows Azure
  • Windows Azure Service Management CmdLets
  • windows live messenger
  • Windows Mobile
  • Windows Phone
  • windows service
  • windows store application
  • Windows Task
  • WinRT
  • word
  • workaround
  • XBox
  • xml
  • xmlns
  • XNA
  • xpath
  • YMesseger
  • Yonder
  • Zip

Blog Archive

  • ►  2013 (139)
    • ►  November (17)
    • ►  October (12)
    • ►  September (10)
    • ►  August (7)
    • ►  July (8)
    • ►  June (15)
    • ►  May (12)
    • ►  April (17)
    • ►  March (16)
    • ►  February (9)
    • ►  January (16)
  • ▼  2012 (251)
    • ►  December (9)
    • ►  November (19)
    • ►  October (26)
    • ►  September (13)
    • ►  August (35)
    • ►  July (28)
    • ▼  June (27)
      • Day 4 of TechEd 2012 - Amsterdam
      • Day 3 of TechEd 2012 - Amsterdam
      • Memento Pattern - the key to unde/redo functionality
      • Day 2 of TechEd 2012 - Amsterdam
      • Serie de turoriale despre debug in Visual Studio
      • Day 1 of TechEd 2012 - Amsterdam
      • How should we treat virtual methods exposed in API...
      • How should we treat virtual methods exposed in APIs
      • XXX takes a dependency on Microsoft.VCLibs.110 fra...
      • How to validate a Windows 8 application
      • Why I cannot use Live account on some Microsoft Se...
      • Applications bugs that can be caused by 'ref' keyword
      • Visual Studio debugging tips and tricks
      • New debugging functionalities in Visual Studio 2012
      • How to secure connection string of a SQL server in...
      • WTF - Package Load Failure - Microsoft.VisualStudi...
      • Some cool stuff debugging with Debugger Canvas
      • Debugging multithreaded applications in Visual Studio
      • Could this be a good case when to use 'params'
      • The provided URI scheme 'file' is invalid; expecte...
      • Base Visual Studio debugging functionalities
      • How to manual create and restore a database from S...
      • Fundamental books for a software engineer (developer)
      • Windows 2008 Server + Office 2007 = InteropService...
      • How to secure connection string of a SQL server in...
      • How to create a setup package for a Metro Applicat...
      • How to backup SQL Azure database using blobs or Da...
    • ►  May (24)
    • ►  April (18)
    • ►  March (17)
    • ►  February (20)
    • ►  January (15)
  • ►  2011 (127)
    • ►  December (11)
    • ►  November (20)
    • ►  October (8)
    • ►  September (8)
    • ►  August (8)
    • ►  July (10)
    • ►  June (5)
    • ►  May (8)
    • ►  April (9)
    • ►  March (14)
    • ►  February (20)
    • ►  January (6)
  • ►  2010 (26)
    • ►  December (1)
    • ►  November (1)
    • ►  October (1)
    • ►  June (2)
    • ►  May (1)
    • ►  April (4)
    • ►  March (1)
    • ►  February (1)
    • ►  January (14)
Powered by Blogger.

About Me

Unknown
View my complete profile