您的位置:首页 > 其它

【软考学习】设计模式——备忘录模式

2018-01-31 23:10 218 查看
【背景】

设计模式是非常重要的一块知识,每个设计模式都值得深入了解和学习。

【内容】

结构型设计模式总结:

备忘录设计模式总结:
    一、定义:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象回复到原先保存的状态。

    二、UML结构图:



    三、代码实现:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 备忘录模式_基本代码
{
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.Read();
}
}

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 Memento (string state)
{
this.state = state;
}

public string State
{
get { return state; }
}
}

class Caretaker
{
private Memento memento;
public Memento Memento
{
get { return memento; }
set { memento = value; }
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: