O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.35. Rolling Back Object Changes

Problem

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.

Solution

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required