打电脑游戏的时候,因为游戏很难在短时间内打完,所以希望能在想退出游戏的时候将游戏的状态保存,等有时间的时候,再恢复游戏的状态继续玩,假设我们只需要保存游戏的:时间,地点,进度这3个参数(一般我们只保存能恢复类状态的最少信息),就可以恢复游戏。这个例子用Memento设计模式实现如下:
/// Memento 设计模式
class MainApp
{
///
/// Entry point into console application.
///
static void Main()
{
//创建游戏
Game g1 = new Game();
g1.Time = "2009/10/18 10:12:15";
g1.Position = "123,113";
g1.Score = 18000;
// 保存游戏状态
ProspectMemory m = new ProspectMemory();
m.Memento = g1.SaveMemento();
//退出游戏
g1 = null;
//重新创建游戏
Game g2 = new Game();
// 恢复游戏状态
g2.RestoreMemento(m.Memento);
// Wait for user
Console.ReadKey();
}
}
//Originator:游戏类
class Game
{
private string _time;//时间
private string _position;//地点
private double _score;//得分数
public string Time
{
get { return _time; }
set
{
_time = value;
Console.WriteLine("Time: " + _time);
}
}
public string Position
{
get { return _position; }
set
{
_position = value;
Console.WriteLine("Position: " + _position);
}
}
public double Score
{
get { return _score; }
set
{
_score = value;
Console.WriteLine("Score: " + _score);
}
}
// 保存状态, 返回一个纪念品
public Memento SaveMemento()
{
Console.WriteLine("\nSaving state --\n");
return new Memento(_time, _position, _score);
}
// 恢复状态,用纪念品
public void RestoreMemento(Memento memento)
{
Console.WriteLine("\nRestoring state --\n");
this.Time = memento.Time;
this.Position = memento.Position;
this.Score = memento.Score;
}
}
//纪念品类
class Memento
{
private string _time;
private string _position;
private double _score;
// Constructor
public Memento(string time, string position, double progress)
{
this._time = time;
this._position = position;
this._score = progress;
}
// Gets or sets Time
public string Time
{
get { return _time; }
set { _time = value; }
}
// Gets or set Position
public string Position
{
get { return _position; }
set { _position = value; }
}
// Gets or sets Score
public double Score
{
get { return _score; }
set { _score = value; }
}
}
//Caretaker类,封装了memento的实例对象。
class ProspectMemory
{
private Memento _memento;
// Property
public Memento Memento
{
set { _memento = value; }
get { return _memento; }
}
}
执行结果如下:
Time: 2009/10/18 10:12:15
Position: 123,113
Score: 18000
Saving state --
Restoring state --
Time: 2009/10/18 10:12:15
Position: 123,113
Score: 18000
没有评论:
发表评论