[Special] Design Pattern - Behavioral Patterns - Memento Pattern

50 篇文章 0 订阅
37 篇文章 0 订阅

2007

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.




Illustration




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







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值