−using System;
using System.Collections.Generic;
using System.Linq;
var editor = new TextEditor();
editor.Write("draft");
ISnapshot saved = editor.Save();
editor.Write("edited");
Console.WriteLine(editor.Restore(saved));
Console.WriteLine(editor.Text);
interface ISnapshot { }
// 복원할 상태의 해석과 변경은 원본 편집기 안에 둔다.
sealed class TextEditor
{
private readonly Guid id = Guid.NewGuid();
private sealed record Snapshot(Guid Owner, string Text) : ISnapshot;
public string Text { get; private set; } = "";
public void Write(string text) => Text = text;
// 외부에는 보관용 토큰만 주고 실제 문자열은 비공개 저장소에 남긴다.
public ISnapshot Save() => new Snapshot(id, Text);
public bool Restore(ISnapshot snapshot)
{
if (snapshot is not Snapshot saved || saved.Owner != id) return false;
Text = saved.Text;
return true;
}
}
+using System;
using System.Collections.Generic;
using System.Linq;
var editor = new TextEditor();
editor.Write("draft");
ISnapshot saved = editor.Save();
editor.Write("edited");
Console.WriteLine(editor.Restore(saved));
Console.WriteLine(editor.Text);
interface ISnapshot { }
// 복원할 상태의 해석과 변경은 원본 편집기 안에 둔다.
sealed class TextEditor
{
private readonly Guid id = Guid.NewGuid();
private sealed record Snapshot(Guid Owner, string Text) : ISnapshot
{
// 레코드의 기본 ToString은 속성 값을 출력하므로 내용을 숨긴다.
public override string ToString() => nameof(ISnapshot);
}
public string Text { get; private set; } = "";
public void Write(string text) => Text = text;
// 스냅샷은 공통 인터페이스로 노출하고 내부 표현은 원래 편집기가 해석한다.
public ISnapshot Save() => new Snapshot(id, Text);
public bool Restore(ISnapshot snapshot)
{
if (snapshot is not Snapshot saved || saved.Owner != id) return false;
Text = saved.Text;
return true;
}
}