备忘录模式是一种对象行为型设计模式,该模式的应用场景有限,主要用来进行数据防丢失,撤销和恢复。对大对象的备份和恢复,应用备忘录模式能够有效节省时间和空间开销。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Designmode.Memento
{
/// <summary>
/// 文本输入类
/// </summary>
public class InputText
{
/// <summary>
/// 文本
/// </summary>
private StringBuilder text = new StringBuilder();
/// <summary>
/// 获取文本
/// </summary>
/// <returns文本></returns>
public string GetText()
{
return text.ToString();
}
/// <summary>
/// 追加文本
/// </summary>
/// <param name="input">输入文本</param>
public void Append(string input)
{
this.text.Append(input);
}
/// <summary>
/// 创建快照
/// </summary>
/// <returns>返回快照</returns>
public Snapshot CreateSnapshot()
{
return new Snapshot(this.text.ToString());
}
/// <summary>
/// 存储快照
/// </summary>
/// <param name="snapshot">快照</param>
public void RestoreSnapshot(Snapshot snapshot)
{
this.text.Clear();
this.text = new StringBuilder(snapshot.GetText());
}
}
}
namespace Designmode.Memento
{
/// <summary>
/// 快照类
/// </summary>
public class Snapshot
{
/// <summary>
/// 快照文本
/// </summary>
private string text;
/// <summary>
/// 构造一个快照对象
/// </summary>
/// <param name="text"></param>
public Snapshot(string text)
{
this.text = text;
}
/// <summary>
/// 获取文本
/// </summary>
/// <returns>文本</returns>
public string GetText()
{
return this.text;
}
}
}
namespace Designmode.Memento
{
public class SnapshotHodler
{
private Stack<Snapshot> snapshots = new Stack<Snapshot> ();
public Snapshot PopSnapshot()
{
return snapshots.Pop();
}
public void PushSnapshot(Snapshot snapshot)
{
snapshots.Push(snapshot);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Designmode.Memento;
namespace Designmode
{
class Program
{
static void Main(string[] args)
{
#region 访问者模式
Extractor extractor = new Extractor();
Compressor compressor = new Compressor();
List<ResourceFile> resources = new List<ResourceFile>();
resources.Add(new PdfFile("1"));
resources.Add(new PPTFile("2"));
resources.Add(new WordFile("3"));
foreach (var file in resources)
{
file.accept(extractor);
file.accept(compressor);
}
#endregion
#region 备忘录模式
InputText inputText = new InputText();
SnapshotHodler snapshotHodler = new SnapshotHodler();
string input = "";
Console.WriteLine("please input cmd: ");
while (input != "q")
{
input =Console.ReadLine();
if (input == ":list")
{
Console.WriteLine(inputText.GetText());
}
else if (input == ":undo")
{
Snapshot snapshot = snapshotHodler.PopSnapshot();
inputText.RestoreSnapshot(snapshot);
}
else
{
snapshotHodler.PushSnapshot(inputText.CreateSnapshot());
inputText.Append(input);
}
}
#endregion
}
}
}