I'm trying to refactor an undo/redo implementation I have but am unsure how to go about it.
public class MyObject
{
public int A;
public int B;
public int C;
}
public abstract class UndoRedoAction
{
protected MyObject myobj;
protected int oldValue;
protected int newValue;
public abstract void Undo();
public abstract void Redo();
}
public class UndoRedoActionA : UndoRedoAction
{
UndoRedoActionA(MyObject obj, int new)
{
myobj = obj;
oldValue = myobj.A;
newValue = new;
myobj.A = newValue;
}
public override void Undo()
{
myobj.A = oldValue;
}
public override void Redo()
{
myobj.A = newValue;
}
}
public class UndoRedoActionB : UndoRedoAction
{
UndoRedoActionB(MyObject obj, int new)
{
myobj = obj;
oldValue = myobj.B;
newValue = new;
myobj.B = newValue;
}
public override void Undo()
{
myobj.B = oldValue;
}
public override void Redo()
{
myobj.B = newValue;
}
}
public class UndoRedoActionC : UndoRedoAction
{
UndoRedoActionC(MyObject obj, int new)
{
myobj = obj;
oldValue = myobj.C;
newValue = new;
myobj.C = newValue;
}
public override void Undo()
{
myobj.C = oldValue;
}
public override void Redo()
{
myobj.C = newValue;
}
}
Obviously, each of the UndoRedoAction child classes have custom functionality as they access different fields, but the functionality they perform on those fields are identical. Is there any clean way, short of making those ints into properties and passing property names (which I would rather not do, magic strings and such), to combine these into a generic UndoRedoAction instead of making a bunch of child classes that all perform the exact same actions on different variables?
I did consider using the Memento pattern which would solve the problem, but it seems quite overkill for a scenario this small and I have no one-way actions to worry about, which is where the Memento pattern is really useful.
Thanks.
Clarification: These UndoRedoAction objects are placed inside a Stack<UndoRedoAction> which serves as the undo cache. More specifically, there are two stacks, one for undo, one for redo, and actions popped off one are pushed onto the other. Additionally, in response to Zaid Masud's response, the variables are not necessarily all ints, or even all the same object type. My example merely did that for simplicity.