天天看點

[Special] Design Pattern - Behavioral Patterns - Memento Pattern

2007
[Special] Design Pattern - Behavioral Patterns - Memento Pattern
Section 6, Chapter 3

Memento Pattern

Concept

The Memento pattern is a way to capture an object's internal state without violating encapsulation of the object, and preserve that state for restoring the object's state at a later time.

Use

Design

Memento patterns have three main objects associated to perform the work of the pattern:

the Originator: the class whose internal state we wish to capture;

the Care-Taker: stores the memento until it is needed to restore that state to the originator;

the Memento: the class in which we store the originator's state.

[Special] Design Pattern - Behavioral Patterns - Memento Pattern

Illustration

[Special] Design Pattern - Behavioral Patterns - Memento Pattern
enum State{NEW,LOADED,CHANGED};

//Originator
class Product
{
	private string _name;
	private string _description;
	private double _cost;
	private State _state = State.NEW;

	public Product(string name, string description, double cost)
	{
		_name = name;
		_description = description;
		_cost = cost;
		_state = State.LOADED;
	}

	public string Name
	{
		get{return _name;}
		set{_name = value;_state = State.CHANGED;}
	}
	public string Description
	{
		get{return _description;}
		set{_description = value;_state = State.CHANGED;}
	}
	public double Cost
	{
		get{return _cost;}
		set{_cost = value;_state = State.CHANGED;}
	}

	public State State
	{
		get{return _state;}
	}
	
	public ProductMemento Memento
	{
		get{return new ProductMemento(_name, _description, _cost, _state);}
	}
	
	public void RestoreMemento(ProductMemento memento)
	{
		this._name = memento.Name;
		this._description = memento.Description;
		this._cost = memento.Cost;
		this._state = memento.State;
	}

}

//Memento
class ProductMemento
{
	.....
	public ProductMemento(string name, string description, double cost, State state)
	{
		this._name = name;
		this._description = description;
		this._cost = cost;
		this._state = state;
	}

	public string Name
	{
		get{return _name;}
	}
	public string Description
	{
		get{return _description;}
	}
	public double Cost
	{
		get{return _cost;}
	}
	public State State
	{
		get{return _state;}
	}
}

//Caretaker
class ProductStateMemory
{
	// Fields
	private ProductMemento _memento;
	// Properties
	public ProductMemento Memento
	{
		set{ _memento = value; }
		get{ return _memento; }
	}
}
           
Product product = new Product("Product A", "The first Product in inventory", 50.00);
// output

ProductStateMemory memory = new ProductStateMemory();
memory.Memento = product.Memento;

product.Name = "Product A(2)";
product.Description = "We have a change";
product.Cost = 60.00;
// output

product.RestoreMemento(memory.Memento);
// output