Design patterns: Memento

in design-patterns •  7 years ago 

girlsmemento.jpg

We are starting another design pattern today, it is called Memento, it is a very simple to understand pattern, also the main picture of this article also translates the pattern, at the same time very attracting attention :) mainly it is mean that you can restore the state of the object to the previous one, the pattern is more precisely explain further in the article :)


Discussion

The main purpose of the Memento pattern is to save the internal state of an object and the possibility of restoring it again if necessary, without disturbing encapsulation.

The implementation of this pattern consists mainly of three classes:

Originator - a class that saves and restores the state of the object.

Caretaker - a class that stores all states of the object on which it operates and returns these states and adds new states of the object.

Memento- class that stores the current state of the object, its state can be read by the Originator class.

A great example of using the Memento pattern is, for example, restoring previous versions of plugins in wordpress if you used wordpress and you had the WP Rollback plugin installed, it was a new button next to the plugin name the Rollback that is used to restore the plugin to the previous version, as shown in the picture below.

mementorollback.png

The creators of this plugin used the Memento pattern for 100% :) Memento is also used in games, when the player wants to load the previous state of the previously saved game.


Intent

Saving the internal state of the object, and if it necessary, restoring the previously saved state of the object.
Non-violation of encapsulation of the object on which we operate.


Problem

The problem in which you use the memento pattern is very simple :) you want to do a function to save and load the state of the game or make a mechanism to restore your program, which we assume you are now creating to the previous version, in this case it will be best to use memento :)

depositphoto.jpg

Those mature ones know what's going on in the picture above


Use when:

You need to restore the state of the object to its previous state.


Structure

The UML diagram of the memento pattern looks like this:

Memento.png

The explanation of the operation of these classes is already in the Discussion section at the top of the article, so I probably do not have to repeat myself :)

I know you feel very smart

smartmementos.jpg

However, it's time to go to the code :) For real work :)

Let's start with the Memento class.

namespace MementoScheme
{
    class Memento
    {
        private string state;

        public Memento(string state)
        {
            this.state = state;
        }

        public string getState()
        {
            return state;
        }
    }
}

As you can see, this class, as it was explained earlier, stores and returns the current state of the object.

Caretaker class.

namespace MementoScheme
{
    class Caretaker
    {
        private List<Memento> mementos = new List<Memento>();

        public void addMemento(Memento m)
        {
            mementos.Add(m);
        }

        public Memento getMemento(int index)
        {
            return mementos[index];
        }
    }
}

And Originator class.

namespace MementoScheme
{
    class Originator
    {
        private string state;

        public void setState(string state)
        {
            Console.WriteLine("Originator: Setting state to " + state);
            this.state = state;
        }

        public Memento save()
        {
            Console.WriteLine("Originator: Saving to Memento.");
            return new Memento(state);
        }

        public void restore(Memento m)
        {
            state = m.getState();
            Console.WriteLine("Originator: State after restoring from Memento: " + state);
        }
    }
}

As it has been said before, this class, as you can see, has methods responsible for saving and restoring the state of the object. In the save() method, we need to get the current state of the object, so we must use the Memento class the same in the restore() method.

Once again I repeat the explanation of the function of all these classes is in the Discussion section at the top of the article :)

Of course, the customer was left who uses these classes.

namespace MementoScheme
{
    public class MementoDemo
    {
        public static void Main(String[] args)
        {
            Caretaker caretaker = new Caretaker();
            Originator originator = new Originator();
            originator.setState("State1");
            originator.setState("State2");
            caretaker.addMemento(originator.save());
            originator.setState("State3");
            caretaker.addMemento(originator.save());
            originator.setState("State4");
            originator.restore(caretaker.getMemento(1));

            Console.ReadLine();
        }
    }
}

Result:

mementoscheme.png


Real-life example

Replacing the brake drum

Suppose we have to replace the brake drum in the car and it has to do a robot for us.

mainrobot.png

It requires to undermine the car and to remove the wheel then change the brake drum and return to the previous state to put the wheel and normally put the car :) In the robot that has to do it for us it is will be well to upload software using the pattern Memento :) For a better understanding is the picture below.

Memento_example.png

And again to the code :) Let's do it in the order as in the previous example :) In total, I will not need the code even seems to explain to me because it is practically the same as in the previous example only the names are different :)

So we start from the Memento class in our case it's called Car.

namespace Mechanic
{
    class Car
    {
        private string state;

        public Car(string state)
        {
            this.state = state;
        }

        public string getState()
        {
            return state;
        }
    }
}

You can see that the same as previously only the class name is different :)

Caretaker class.

namespace Mechanic
{
    class Caretaker
    {
        private List<Car> mementos = new List<Car>();

        public void addMemento(Car m)
        {
            mementos.Add(m);
        }

        public Car getMemento(int index)
        {
            return mementos[index];
        }
    }
}

Same as previously only also names are different as well :)

The Originator class in our case is called Mechanic.

namespace Mechanic
{
    class Mechanic
    {
        private string state;

        public void setState(string state)
        {
            Console.WriteLine(state);

            this.state = state;
        }

        public Car save()
        {
            return new Car(state);
        }

        public void restore(Car m)
        {
            state = m.getState();
            Console.WriteLine("Returning to the previous work.");
            Console.WriteLine(state);
        }
    }
}

The logic of this class is the same as in the previous example :)

And client :)

namespace Mechanic
{
    class Program
    {
        static void Main(string[] args)
        {
            Caretaker caretaker = new Caretaker();
            Mechanic mechanic = new Mechanic();
            mechanic.setState("The brake drum is in use. Begin of work");
            caretaker.addMemento(mechanic.save());
            mechanic.setState("The brake drum is available to use. End of work");
            mechanic.restore(caretaker.getMemento(0));

            Console.ReadLine();
        }
    }
}

Result:

mementomechanic.png


Relations with other design patterns

Memento is sometimes used in conjunction with the iterator to control the state of iteration

Summary

That’s all about Memento.

Link to github with the whole code from this article: https://github.com/Slaw145/Memento

This content also you can find on my blog devman.pl: http://devman.pl/programtech/design-patterns-memento/

And on medium: https://medium.com/@sawomirkowalski/design-patterns-memento-f9fc1e127316

If you recognise it as useful, share it with others so that others can also use it.

Leave upvote and follow and wait for next articles :) .

In the next article, we will talk about the Command pattern.

And NECESSERILY join the DevmanCommunity community on fb, part of the community is in one place

– site on fb: Devman.pl-Slawomir Kowalski

– group on fb: DevmanCommunity

Ask, comment underneath at the end of the post, share it, rate it, whatever you want.

Illustrations, pictures and diagrams are from: https://sourcemaking.com/design_patterns/memento

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!