1. 程式人生 > >設計模式のMementoPattern(備忘錄模式)----行為模式

設計模式のMementoPattern(備忘錄模式)----行為模式

ron post AI tasks style 一次 blog tro sin

一、產生背景

意圖:在不破壞封裝性的前提下,捕獲一個對象的內部狀態,並在該對象之外保存這個狀態。

主要解決:所謂備忘錄模式就是在不破壞封裝的前提下,捕獲一個對象的內部狀態,並在該對象之外保存這個狀態,這樣可以在以後將對象恢復到原先保存的狀態。

何時使用:很多時候我們總是需要記錄一個對象的內部狀態,這樣做的目的就是為了允許用戶取消不確定或者錯誤的操作,能夠恢復到他原先的狀態,使得他有"後悔藥"可吃。

二、實現方式

  • 發起人角色:記錄當前時刻的內部狀態,負責創建和恢復備忘錄數據。
  • 備忘錄角色:負責存儲發起人對象的內部狀態,在進行恢復時提供給發起人需要的狀態。
  • 管理者角色:負責保存備忘錄對象。

三、實例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MementoPattern
{
    //備忘錄模式
    class Program
    {
        static void Main(string[] args)
        {

            Originator o = new Originator();
            o.State = "On
"; Caretaker c = new Caretaker(); c.Memento = o.CreateMemento(); o.State = "Off"; o.SetMemento(c.Memento); Console.ReadLine(); } } public class Memento { private string _state; public Memento(string state) {
this._state = state; } public string State { get { return _state; } } } public class Originator { private string _state; public string State { get { return _state; } set { _state = value; Console.WriteLine("State = " + _state); } } public Memento CreateMemento() { return (new Memento(_state)); } public void SetMemento(Memento memento) { Console.WriteLine("Restoring state..."); State = memento.State; } } public class Caretaker { private Memento _memento; public Memento Memento { get { return _memento; } set { _memento = value; } } } }

四、模式分析

優點: 1、給用戶提供了一種可以恢復狀態的機制,可以使用戶能夠比較方便地回到某個歷史的狀態。 2、實現了信息的封裝,使得用戶不需要關心狀態的保存細節。

缺點:消耗資源。如果類的成員變量過多,勢必會占用比較大的資源,而且每一次保存都會消耗一定的內存。

設計模式のMementoPattern(備忘錄模式)----行為模式