Memento Pattern Code Review
Use the Memento Pattern
Code Review
- Memento Pattern Code Review: Define the Memento Object
- Memento Pattern Code Review: Define the Game, Caretaker and Simulator Objects
- Memento Pattern Code Review: Use the Memento Pattern
Code Walkthrough
The Program class creates the Game object and an array of Caretaker objects.
class Program
{
static void Main(string[] args)
{
Int32 move;
Console.WriteLine("Let's practice TicTacToe"); Console.WriteLine("Commands are:\n1-9 for a position\nU-n where n is the number of moves to undo\nQ to end");
Game game = new Game();
Caretaker[] c = new Caretaker[10]; game.DisplayBoard(); move = 1;
Simulator simulator = new Simulator();
foreach (String command in simulator) { Console.WriteLine("\nMove {0} for {1}: {2}", move,game.Player,command);
if (command[0] == 'Q') break;
c[move] = new Caretaker(); c[move].Memento = game.Save();
if (command[0] == 'U') { Int32 back = Int32.Parse(command.Substring(2, 1)); if (move - back > 0) { game.Restore(c[move - back].Memento); } else { Console.WriteLine("Too many moves back"); } move = move - back - 1; } else { game.Play(Int32.Parse(command.Substring(0, 1))); } game.DisplayBoard(); move++; } Console.WriteLine("Thanks for laying"); Console.Read(); } }
Console.WriteLine("Let's practice TicTacToe"); Console.WriteLine("Commands are:\n1-9 for a position\nU-n where n is the number of moves to undo\nQ to end");
Game game = new Game();
Caretaker[] c = new Caretaker[10]; game.DisplayBoard(); move = 1;
Simulator simulator = new Simulator();
foreach (String command in simulator) { Console.WriteLine("\nMove {0} for {1}: {2}", move,game.Player,command);
if (command[0] == 'Q') break;
c[move] = new Caretaker(); c[move].Memento = game.Save();
if (command[0] == 'U') { Int32 back = Int32.Parse(command.Substring(2, 1)); if (move - back > 0) { game.Restore(c[move - back].Memento); } else { Console.WriteLine("Too many moves back"); } move = move - back - 1; } else { game.Play(Int32.Parse(command.Substring(0, 1))); } game.DisplayBoard(); move++; } Console.WriteLine("Thanks for laying"); Console.Read(); } }
Each Caretaker object will store an instance of the Memento object. The input data provided in the Simulator object is processed and at the same time, application state is stored by the Memento object.
Printer Friendly Version
Add to Favourites
DotNet Kicks
Digg
del.icio.us
Live Favourites
ma.gnolia
reddit
Slashdot
Technorati
Yahoo!