3.35. Rolling Back Object Changes


You have an object that allows its state to be changed. However, you do not want these changes to become permanent if other changes to the system cannot be made at the same time. In other words, you want to be able to roll back the changes if any of a group of related changes fails.


Use the memento design pattern to allow your object to save its original state in order to roll back changes. The SomeDataOriginator class defined for this recipe contains data that must be changed only if other system changes occur. Its source code is:

using System; using System.Collections; public class SomeDataOriginator { public SomeDataOriginator( ) {} public SomeDataOriginator(int state, string id, string clsName) { this.state = state; this.id = id; this.clsName = clsName; } private int state = 1; private string id = "ID1001"; private string clsName = "SomeDataOriginator"; public string ClassName { get {return (clsName);} set {clsName = value;} } public string ID { get {return (id);} set {id = value;} } public void ChangeState(int newState) { state = newState; } public void Display( ) { Console.WriteLine("State: " + state); Console.WriteLine("Id: " + id); Console.WriteLine("clsName: " + clsName); } // Nested Memento class used to save outer class's state internal class Memento { internal Memento(SomeDataOriginator data) { this.state = data.State; this.id = data.id; this.clsName = data.clsName; originator = data; } private SomeDataOriginator originator ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.