简体   繁体   中英

Some explanation on memento

I have checked every where, and read countless article. I even went on some Chinese forum looking for answers. The thing is i can't fully understand c# memento pattern. Different articles show different ways on doing it, i cant understand it properly. Most of the articles only show simple stuff like string memento. I am trying to understand how to do a undo function and need help and also, how can you do a undo function on a public partial class?, i just need a small example showing public partial class memento. Thanks in advance.

Basically, a memento is a way of saving and restoring an object's state. But it goes a bit beyond that: it's a way of preserving encapsulation. So if the object whose state you want to save has some private members, the memento pattern is a way of being able to access those members in a limited way.

For an example, let's say we have a 2D character doing a drunken walk around a map:

public class Sprite
{
    private double _x = 0, _y = 0;
    public void Run()
    {
        var random = new byte[2];
        new Random().NextBytes(random);
        _x += (double)random[0];
        _y += (double)random[1];
    }

    public void Render()
    {
        Console.WriteLine("({0}, {1})", _x, _y);
    }
}

Let's say we don't want to expose x and y as public members, but we want to be able to save the object's state. Then we can create a memento class that encapsulates the object's state:

public class SpriteMemento
{
    public double X { get; set; }
    public double Y { get; set; }
}

The Sprite class can accept a memento object to restore its state, and provide one to save:

public class Sprite
{
    // ...

    public SpriteMemento Memento
    {
        get { return new SpriteMemento { X = _x, Y = _y }; }
    }

    public void Restore(SpriteMemento memento)
    {
        if (memento == null)
            return; 

        _x = memento.X;
        _y = memento.Y;
    }
}

Now, let's say we have another class that is controlling the run. We can now have this class provide an "undo" feature:

static void Main(string[] args)
{
    var sprite = new Sprite();
    SpriteMemento state = null;
    while (true)
    {
        string input = Console.ReadLine();
        if (input == "run")
            sprite.Run();
        else if (input == "save")
            state = sprite.Memento;
        else if (input == "undo")
            sprite.Restore(state);

        sprite.Render();
    }
}

As far as a partial class, there is really no difference -- just tack on "partial" to the Sprite class above, and the memento pattern is still intact.

Reference: Memento Design Pattern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM