C#でデザインパターン「Mementoパターン」

C# コンピュータ
C#

オブジェクトの状態を外部に公開せずに保存し、後でその状態に復元するためのパターンみたいです。

ウィキペディアの「Mementoパターン」のページ
Memento パターン - Wikipedia

サンプルコード

using System.ComponentModel;
using System.Data;

/// <summary>
/// Mementoパターンのサンプルコード
/// </summary>
interface IMemento<T>
{
    T State { get; set; }
}
class TextEditor
{
    public string Text {get; set;} = "";
    public Memento Save()
    {
        // 状態の保存
        return new Memento(){ State = this.Text};
    }
    public void Restore(Memento memento)
    {
        // 状態の復元
        Text = memento.State;
    }

}
class Memento : IMemento<string>
{
    public string State { get; set; } = "";
}
class History<T>
{
    Stack<T> _mementos = [];

    public void Push(T memento)
    {
        _mementos.Push(memento);
    }
    public T Pop()
    {
        return _mementos.Pop();
    }

}
static class Program
{
    static public void Main()
    {
        TextEditor editor = new TextEditor();
        History<Memento> history = new History<Memento>();

        editor.Text = "最初のテキスト";
        history.Push(editor.Save());

        editor.Text = "2番目のテキスト";
        history.Push(editor.Save());

        editor.Text = "3番目のテキスト";
        Console.WriteLine($"現在のテキスト: {editor.Text}");
        // 現在のテキスト: 3番目のテキスト

        editor.Restore(history.Pop());
        Console.WriteLine($"現在のテキスト: {editor.Text}");
        // 現在のテキスト: 2番目のテキスト

        editor.Restore(history.Pop());
        Console.WriteLine($"現在のテキスト: {editor.Text}");
        // 現在のテキスト: 最初のテキスト
    }
}

コメント