设计模式——备忘录模式(Memento)
来源:互联网 发布:java字符串转整型 编辑:程序博客网 时间:2024/05/01 22:19
作用:
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
UML结构图:
解析:
Memento模式中封装的是需要保存的状态,当需要恢复的时候才取出来进行恢复。原理很简单,实现的时候需要注意一个地方:窄接口和宽接口。所谓的宽接口就是一般意义上的接口,把对外的接口作为public成员;而窄接口反之,把接口作为private成员,而把需要访问这些接口函数的类作为这个类的友元类,也就是说接口只暴露给了对这些接口感兴趣的类,而不是暴露在外部。下面的实现就是窄实现的方法来实现的。
实现:
Memento.h#ifndef MEMENTO_H#define MEMENTO_H#include <string>typedef std::string State;class Memento;class Originator{public: Originator(const State& rState); Originator(); ~Originator(); Memento* CreateMemento(); void SetMemento(Memento* pMemento); State GetState(); void SetState(const State& rState); void RestoreState(Memento* pMemento); void PrintState();private: State m_State;};// 把Memento的接口函数都设置为私有的,而Originator是它的友元,// 这样保证了只有Originator可以对其访问class Memento{private: friend class Originator; Memento(const State& rState); void SetState(const State& rState); State GetState(); State m_State;};#endif
Memento.cpp#include "Memento.h"#include <iostream>Originator::Originator(){}Originator::Originator(const State& rState) : m_State(rState){}Originator::~Originator(){}State Originator::GetState(){ return m_State;}void Originator::SetState(const State& rState){ m_State = rState;}Memento* Originator::CreateMemento(){ return new Memento(m_State);}void Originator::RestoreState(Memento* pMemento){ if (NULL != pMemento) { m_State = pMemento->GetState(); } }void Originator::PrintState(){ std::cout << "State = " << m_State << std::endl;}Memento::Memento(const State& rState) : m_State(rState){}State Memento::GetState(){ return m_State;}void Memento::SetState(const State& rState){ m_State = rState;}
Main.cpp#include "Memento.h"int main(){ // 创建一个原发器 Originator* pOriginator = new Originator("old state"); pOriginator->PrintState(); // 创建一个备忘录存放这个原发器的状态 Memento *pMemento = pOriginator->CreateMemento(); // 更改原发器的状态 pOriginator->SetState("new state"); pOriginator->PrintState(); // 通过备忘录把原发器的状态还原到之前的状态 pOriginator->RestoreState(pMemento); pOriginator->PrintState(); delete pOriginator; delete pMemento; return 0;}
- 设计模式——备忘录模式(Memento)
- 【设计模式】—— 备忘录模式Memento
- 设计模式—Memento备忘录模式
- JAVA设计模式—备忘录模式(Memento)
- Memento(备忘录)设计模式
- 备忘录模式——Memento
- 设计模式 Design Parttern ——备忘录模式Memento
- java设计模式19——备忘录模式(Memento)
- Java设计模式——备忘录模式(Memento)
- java设计模式——备忘录模式(Memento Pattern)
- 设计模式——备忘录(Memento Pattern)模式
- 设计模式学习笔记——备忘录(Memento)模式
- Java设计模式——备忘录模式(Memento Pattern)
- 设计模式学习笔记(十七)—Memento备忘录模式
- JAVA设计模式(19) —<行为型>备忘录模式(Memento)
- 设计模式学习—备忘录模式(Memento Design Pattern)
- 设计模式的征途—20.备忘录(Memento)模式
- 设计模式----Memento(备忘录)模式
- Linux学习内核移植相关笔记第4部分
- 飞鸽传书系统上开发是一件多么惬意的事情
- 高效引用传值的方案
- HTML中使背景图片自适应浏览器大小
- FriendlyARM tiny6410 一步一步学与思(2)---buttons application
- 设计模式——备忘录模式(Memento)
- Java图形界面汉诺塔
- 结构体如何使用NSData包装
- linux基础之使用异步 I/O 大大提高应用程序的性能 学习何时以及如何使用 POSIX AIO API
- 开发随笔-.net ThreadPool
- ioctl Socket Control Operations
- 辗转相除
- C#访问PostGreSQL数据库
- Linux下的多进程编程初步