Memento Design Pattern in Visual Basic .NET

Definition

Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.

This pattern is used to save the internal state of an object when it changes  state of over the time. You can use save points when you save the state so that you can retrieve the state of the object

This is the UML diagram to show the Memento Design Pattern
Memento Design Pattern UML

Participant

Now we will see the participant in the UML diagram

Originator

  • Hold reference to memento object
  • Save state in memnto

Memento

  • Stores internal state of the Originator object
  • Protects against access by objects other than the originator.

CareTaker

  • Is responsible for the memento’s safekeeping.
  • Never operates on or examines the contents of a memento.

Memento Design Pattern Example in VB.NET

To understand the memento design pattern completely we will code one example using VB.NET
You have Game class to hold the score of two teams. when they are playing you can store the score with save point so that you can undo using save points.
You can have a look at the UML diagram of the following example
Memento Design Pattern Example UML
To implement the above example I have used following code
Game Class (Originator)

In this Originator we have the scores of Team A and Team B also we have reference to GameCareTaker object

GameMemento Class (Memento)

This is our Memento class and it has same properties like originator class

GameCareTaker Class (CareTaker)

This is our CareTaker class. This will save the Memeto and retrive the Memnto once you give the save point details

 

This is the Client program to test the design pattern

Output of the above Example

 

Leave a Reply

Your email address will not be published. Required fields are marked *