private static void approach2() { try { Console.WriteLine("APPROACH 2"); Speedometer2 speedo = new Speedometer2(); speedo.CurrentSpeed = 50; speedo.CurrentSpeed = 100; Console.WriteLine("Current speed: " + speedo.CurrentSpeed); Console.WriteLine("Previous speed: " + speedo.PreviousSpeed); // Save the state of 'speedo' SpeedometerMemento2 memento = new SpeedometerMemento2(speedo); // Change the state of 'speed' speedo.CurrentSpeed = 80; Console.WriteLine("After setting to 80..."); Console.WriteLine("Current speed: " + speedo.CurrentSpeed); Console.WriteLine("Previous speed: " + speedo.PreviousSpeed); // Restore the state of 'speedo' Console.WriteLine("Now restoring state..."); speedo = memento.RestoreState(); Console.WriteLine("Current speed: " + speedo.CurrentSpeed); Console.WriteLine("Previous speed: " + speedo.PreviousSpeed); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.Write(ex.StackTrace); } }
public SpeedometerMemento2(Speedometer2 speedometer) { // Serialize... Stream stream = File.Open("speedometer.ser", FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, speedometer); stream.Close(); }