Click here to Skip to main content
15,883,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was asked to explain memento pattern in an interview. I did something like this.
Does this code look like Memento pattern? Where is it different?

C#
namespace ConsoleApplication1
{
    class Originator:ICloneable
    {
        public string a;
        public int b;

        public object Clone()
        {
            Originator o = new Originator();
            o.a = this.a;
            o.b = this.b;
            return o;
        }
    }

    class CareTaker
    {
        List<Originator> l = new List<Originator>();

        public void SaveMemento(Originator o)
        {
             l.Add((Originator)o.Clone());
        }

        public Originator RetrieveMemento(int i)
        {
            return l[i];
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            CareTaker c = new CareTaker();
            Originator o = new Originator();
            c.SaveMemento(o);

        }   
    }
}
Posted
Updated 21-Mar-13 1:46am
v2

1 solution

If you were asked to "explain" the design pattern then there was no need to write any code - you'd have been better off putting in words what the design pattern tries to achieve and possible adding a UML diagram.

Failing that you could have put some comments in your code to demonstrate your knowledge of the pattern.

Your Main function should actually show a change of state and then roll-back to the previous state to fully demonstrate the pattern.

Have a look at this example for comparison http://www.dofactory.com/Patterns/PatternMemento.aspx[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900