意圖
在不破壞封裝性的前提條件下,捕獲一個(gè)對(duì)象的內(nèi)部狀態(tài),然后在該對(duì)象之外保存這個(gè)狀態(tài)。以后在需要的時(shí)候可以將該對(duì)象恢復(fù)到原先保存的狀態(tài)。
結(jié)構(gòu)
1.Memento
(備忘錄):保存
Originator
(原發(fā)器)對(duì)象的內(nèi)部狀態(tài),
Originator
根據(jù)需要決定保存哪些內(nèi)部狀態(tài),防止自身以外的其它對(duì)象訪問(wèn)備忘錄。備忘錄實(shí)際上是由兩個(gè)接口,其中
Caretaker
(管理者)只能看到備忘錄的窄接口,即它只能將備忘錄傳遞給其他對(duì)象;而原發(fā)器可以看到一個(gè)寬接口,允許他訪問(wèn)回到原先狀態(tài)所需的所有數(shù)據(jù),理想的情況是只允許生成原發(fā)器訪問(wèn)本備忘錄的內(nèi)部狀態(tài)。
2.Originator
:創(chuàng)建一個(gè)備忘錄以記錄當(dāng)前時(shí)刻內(nèi)部狀態(tài),使用備忘錄恢復(fù)內(nèi)部狀態(tài)。
3.Caretaker
:負(fù)責(zé)保存?zhèn)渫洠荒芴幚砥渲械膬?nèi)容。
使用場(chǎng)合
需要保存對(duì)象在某一時(shí)刻的狀態(tài),并在以后需要的時(shí)候恢復(fù)到這個(gè)狀態(tài)。同時(shí)又不希望暴露對(duì)象的視線細(xì)節(jié),破壞對(duì)象的封裝性,這時(shí)需要使用備忘錄模式。
效果
備忘錄模式在不破壞封裝性的前提下,實(shí)現(xiàn)對(duì)對(duì)象內(nèi)部狀態(tài)的外部保存。但如果保存的狀態(tài)過(guò)多,或者設(shè)計(jì)不合理,則將產(chǎn)生過(guò)多的備忘錄對(duì)象而占用大量的系統(tǒng)資源。
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;
}
}
}
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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