备忘录(Memento):在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象外保存这个状态。这样就可将该对象恢复到原先保存的状态。

1、Originator(发起人):负责创建一个Memento备忘录,用以记录当前时刻它的内部状态,并可使用备忘录恢复内部状态。Originator可根据需要决定Memento存储 Originator的哪些内部状态。

2、 Memento(备忘录):负责存储Originator内部状态,并可防止Originator以外的对象访问备忘录Memento。备忘录有两个接口,Caretaker只能看到备忘录的窄接口,它只能将备忘录传递给其他对象。Originator能看到一个粗接口,允许它访问返回到先前状态的所有数据。

using System;
using System.Collections.Generic;
using System.Text;

namespace Memento
{
    
class Program
    {
        
static void Main(string[] args)
        {
            Originator o 
= new Originator();
            o.State 
= "on";
            o.Show();
            Caretaker c 
= new Caretaker();
            c.Memento 
= o.CreateMemento();
            o.State 
= "off";
            o.Show();
            o.SetMemento(c.Memento);
            o.Show();
            Console.ReadLine();
        }
    }
    
class Originator
    {
        
private string _state;

        
public string State
        {
            
get { return _state; }
            
set { _state = value; }
        }
        
public Memento CreateMemento()
        {
            
return (new Memento(State));
        }
        
public void SetMemento(Memento memento)
        {
            State 
= memento.State;
        }
        
public void Show()
        {
            Console.WriteLine(
"State="+State);
        }
    }
    
class Memento
    {
        
private string _state;

        
public string State
        {
            
get { return _state; }
            
set { _state = value; }
        }
        
public Memento(string state)
        {
            
this._state = state;
        }
 
    }
    
class Caretaker
    {
        
private Memento memento;

        
internal Memento Memento
        {
            
get { return memento; }
            
set { memento = value; }
        }
 
    }
}

相关文章:

  • 2018-10-29
  • 2021-10-02
  • 2021-06-07
  • 2021-07-08
  • 2021-09-14
  • 2022-01-14
  • 2021-10-14
猜你喜欢
  • 2022-01-06
  • 2022-12-23
  • 2021-05-18
  • 2022-02-11
  • 2021-10-18
  • 2021-11-03
相关资源
相似解决方案