Memento Pattern Code Review

Define the Game, Caretaker and Simulator Objects

Code Review

Code Walkthrough

The Game class (object) represents the Originator component that generates the application data.

[Serializable] class Game { private Char[] m_board = { 'X', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
public Char Player { get; set; }
public Game() { this.Player = 'X'; }
public void Play(Int32 pos) { this.m_board[pos] = this.Player; if (this.Player == 'X') { this.Player = 'O'; } else { this.Player = 'X'; } this.m_board[0] = Player; } public Memento Save() { Memento memento = new Memento(); return memento.Save(this.m_board); } public void Restore(Memento memento) { this.m_board = (Char[])memento.Restore(); this.Player = this.m_board[0]; } public void DisplayBoard() { Console.WriteLine(); for (Int32 i = 1; i <= 9; i+=3) { Console.WriteLine("{0} | {1} | {2}", this.m_board[i], this.m_board[i+1], this.m_board[i+2]); if (i < 6) Console.WriteLine("---------"); } } }

The Game class (object) invokes the Save() and Restore() methods of the Memento class (object).

The Caretaker class (object) stores an instance of the Memento class (object).

class Caretaker { public Memento Memento { get; set; } }

The Simulator class (object) stores the input data that is used by the Game class (object).

class Simulator : IEnumerable { String[] m_moves = { "5", "3", "1", "6", "9", "U-2", "9", "6", "4", "2", "7", "8", "Q" };
public IEnumerator GetEnumerator() { foreach (String element in this.m_moves) { yield return element; } } }