设计模式-行为-备忘录
原创
©著作权归作者所有:来自51CTO博客作者shixin_0125的原创作品,请联系作者获取转载授权,否则将追究法律责任
#pragma once
#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;
};
class Memento
{
private:
friend class Originator;
Memento(const State& rState);
void SetState(const State& rState);
State GetState();
State m_State;
};
#endif
#include "StdAfx.h"
#include "memento_impl.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;
}
#include "stdafx.h"
#include "memento_impl.h"
#include <stdlib.h>
int _tmain(int argc, _TCHAR* argv[])
{
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;
system("pause");
return 0;
}