Command Pattern
Summary: Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.
Sample Code
Code
public class DigitalCameraFirmware
{
public string Name { get; set; }
public byte[] Data { get; set; }
public Memento SaveMemento()
{
return new Memento(Name, Data);
}
public void RestoreMemento(Memento memento)
{
this.Name = memento.Name;
this.Data = memento.Data;
}
}
public class Memento
{
public string Name { get; private set; }
public byte[] Data { get; private set; }
public Memento(string name, byte[] data)
{
this.Name = name;
this.Data = data;
}
}
public class FirmwareMemory
{
private Memento _memento;
public Memento Memento
{
set { _memento = value; }
get { return _memento; }
}
}
Usage
var cameraFirmware = new DigitalCameraFirmware { Name = "v1.0", Data = new byte[1024] };
System.Console.WriteLine($"Current firmware version: {cameraFirmware.Name}");
FirmwareMemory memory = new FirmwareMemory();
memory.Memento = cameraFirmware.SaveMemento();
cameraFirmware.Name = "v2.0";
cameraFirmware.Data = new byte[1024];
System.Console.WriteLine($"Current firmware version: {cameraFirmware.Name}");
// something fails with the new firmware, so we want to restore the previous one
cameraFirmware.RestoreMemento(memory.Memento);
System.Console.WriteLine($"Current firmware version: {cameraFirmware.Name}");
Output
Current firmware version: v1.0
Current firmware version: v2.0
Current firmware version: v1.0
Comments
Post a Comment