设计模式之备忘录模式
备忘类
#pragma once #include <string> class Memento { private: friend class Originator; typedef std::string State; // 作用域为类内 Memento(); ~Memento(); Memento(const State &state); void SetState(const State &state); State GetState(); private: State m_state; };
#include "Memento.h" typedef std::string State; // 作用域为这个cpp文件 Memento::Memento() { } Memento::~Memento() { } Memento::Memento(const State &state) { m_state = state; } State Memento::GetState() { return m_state; } void Memento::SetState(const State &state) { m_state = state; }
操作类
#pragma once #include <string> class Memento; class Originator { public: typedef std::string State; public: Originator(); ~Originator(); Originator(const State &state); Memento *GreateMemento(); void SetMemento(Memento *men); void RestoreToMemento(Memento *men); State GetState(); void SetState(const State &state); void PrintState(); private: State m_state; Memento *m_men; };
#include "Originator.h" #include "Memento.h" #include <iostream> typedef std::string State; //作用域为这个cpp文件 Originator::Originator() { m_state = ""; m_men = 0; } Originator::~Originator() { if (m_men) { delete m_men; m_men = NULL; } } Originator::Originator(const State &state) { m_state = state; m_men = 0; } Memento *Originator::GreateMemento() { m_men = new Memento(m_state); return m_men; } State Originator::GetState() { return m_state; } void Originator::SetState(const State &state) { m_state = state; return; } void Originator::PrintState() { std::cout << this->m_state << "..." << std::endl; return; } void Originator::SetMemento(Memento *men) { return; } void Originator::RestoreToMemento(Memento *men) { this->m_state = men->GetState(); }
测试
#include <iostream> #include "Originator.h" #include "Memento.h" #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> int main() { Originator *ori = new Originator(); ori->SetState("old"); ori->PrintState(); Memento *men = ori->GreateMemento(); ori->SetState("new"); ori->PrintState(); ori->RestoreToMemento(men); ori->PrintState(); if (ori) { delete ori; ori = NULL; } _CrtDumpMemoryLeaks(); std::cout << "Hello World!\n"; }

浙公网安备 33010602011771号