好几天没写博客了,前几天在网上看到一个设计模式叫做备忘录模式。觉得还是比较有趣,自己写了个模仿电脑备份的小例子。先看下备忘录模式的介绍吧
备忘录模式(Memento Pattern)又叫做快照模式(Snapshot Pattern)或Token模式,是GoF的23种设计模式之一,属于行为模式。
下面就上一个我写的例子
1.备忘录类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Recover.org.lxh
{
//备忘录角色
public class Memento
{
private string status;
public string Status
{
get {
return status;
}
set {
Console.WriteLine("系统处于:"+this.status);
status = value;
}
}
public Memento(string status)
{
this.status = status;
}
}
}
2.发起人类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Recover.org.lxh
{
//发起人
public class WindowsSystem
{
private string status;
public string Status
{
get {
return status;
}
set {
status = value;
}
}
public Memento createOtherSystem() {
return new Memento(status);
}
public void recoverSystem(Memento m)
{
this.status = m.Status;
}
}
}
3.负责人(备忘录管理者)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Recover.org.lxh
{
//负责人(备忘录管理者)
public class UserComputer
{
private Memento memento;
public Memento recoverMemento()
{
// 恢复系统
return this.memento;
}
public void createMemento(Memento memento)
{
// 保存系统
this.memento = memento;
}
}
}
4.测试类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Recover.org.lxh;
namespace Recover
{
class Program
{
static void Main(string[] args)
{
WindowsSystem Winxp = new WindowsSystem(); // Winxp系统
UserComputer user = new UserComputer(); // 某一用户
Winxp.Status="好的状态"; // Winxp处于好的运行状态
user.createMemento(Winxp.createOtherSystem()); // 用户对系统进行备份,Winxp系统要产生备份文件
Winxp.Status="坏的状态"; // Winxp处于不好的运行状态
Winxp.recoverSystem(user.recoverMemento()); // 用户发恢复命令,系统进行恢复
Console.WriteLine("当前系统处于" + Winxp.Status);
Console.ReadKey();
}
}
}
