意圖
在不破壞封裝性的前提條件下,捕獲一個對象的內部狀態,然后在該對象之外保存這個狀態。以后在需要的時候可以將該對象恢復到原先保存的狀態。
結構
1.Memento
(備忘錄):保存
Originator
(原發器)對象的內部狀態,
Originator
根據需要決定保存哪些內部狀態,防止自身以外的其它對象訪問備忘錄。備忘錄實際上是由兩個接口,其中
Caretaker
(管理者)只能看到備忘錄的窄接口,即它只能將備忘錄傳遞給其他對象;而原發器可以看到一個寬接口,允許他訪問回到原先狀態所需的所有數據,理想的情況是只允許生成原發器訪問本備忘錄的內部狀態。
2.Originator
:創建一個備忘錄以記錄當前時刻內部狀態,使用備忘錄恢復內部狀態。
3.Caretaker
:負責保存備忘錄,但不能處理其中的內容。
使用場合
需要保存對象在某一時刻的狀態,并在以后需要的時候恢復到這個狀態。同時又不希望暴露對象的視線細節,破壞對象的封裝性,這時需要使用備忘錄模式。
效果
備忘錄模式在不破壞封裝性的前提下,實現對對象內部狀態的外部保存。但如果保存的狀態過多,或者設計不合理,則將產生過多的備忘錄對象而占用大量的系統資源。
using System;
namespace MyApp
{
class Program
{
static void Main()
{
GameRole gameRole = new GameRole ( "Killer007" );
gameRole.ShowState();
gameRole.HitBoss();
gameRole.HitBoss();
gameRole.Hitted();
gameRole.ShowState();
gameRole.SetMemento();
gameRole.Hitted();
gameRole.Hitted();
gameRole.Hitted();
gameRole.Hitted();
gameRole.ShowState();
gameRole.GetMemento();
gameRole.ShowState();
Console .ReadKey();
}
}
class GameRole
{
private string account;
private int blood;
private int magic;
private Memento memento;
public GameRole( string account)
{
this .account = account;
blood = 100 ;
magic = 100 ;
}
public void SetMemento()
{
this .memento = new Memento (blood, magic);
}
public void GetMemento()
{
this .blood = memento.Blood;
this .magic = memento.Magic;
}
public void HitBoss()
{
magic -= 20 ;
}
public void Hitted()
{
blood -= 20 ;
}
public void ShowState()
{
Console .WriteLine( "Account:{0}" , account);
Console .WriteLine( " Blood:{0}" , blood.ToString());
Console .WriteLine( " Magic:{0}" , magic.ToString());
Console .WriteLine();
}
}
class Memento
{
private int blood;
private int magic;
public int Blood
{
get
{
return blood;
}
}
public int Magic
{
get
{
return magic;
}
}
public Memento( int blood, int magic)
{
this .blood = blood;
this .magic = magic;
}
}
}
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
