Mementor备忘录模式

  

#ifndef STATE_H
#define STATE_H

#include <iostream>
#include <string>
using namespace std;

class State
{
    public:
        State(string &state):str_state(state) { }
        
        string& GetStateString();
        friend ostream& operator<< ( ostream &os, const State &rhs );
    protected:
        string str_state;
};

#endif
#include "state.h"

ostream& operator<< ( ostream &os, const State &rhs )
{
    os << "State:"<<rhs.str_state << "@" << &rhs <<endl;
    return os;
}

string& State::GetStateString(){
    return this->str_state;
}
#ifndef ORIGINATOR_H
#define ORIGINATOR_H

#include "state.h"
#include "memento.h"

class Originator
{
    public:
        Originator():_state(0){    }
        Originator(State * state):_state(state) {}
        virtual ~Originator();
        
        Memento* CreateMemento();
        void SetMemento(Memento * memento);
        State* GetState() const;
    protected:
        State * _state;
};

#endif
#include "originator.h"

Memento* Originator::CreateMemento(){
    return new Memento(_state);
}
        
void Originator::SetMemento(Memento * memento){
    if(_state) delete _state;
    _state = new State(memento->GetState()->GetStateString());
}

State* Originator::GetState() const{
    return _state;
}

Originator::~Originator(){
    if(_state) delete _state;
}
#ifndef MEMENTO_H
#define MEMENTO_H
#include "state.h"

class Memento
{
    public:
        explicit Memento(State * state);
        ~Memento();
        State * GetState() const;
    protected:
        State * _state;        
};

#endif
#include "memento.h"

Memento::Memento(State * state){
    this->_state = new State(state->GetStateString());
}

Memento::~Memento(){
    if(_state) delete _state;
}

State * Memento::GetState() const{
    return _state;
}
#include <iostream>
#include <string>

#include "originator.h"
#include "memento.h"

using namespace std;

int main(int argc, char** argv) {
    string sold("OldState");
    State * old = new State(sold);
    
    Originator *pOrigin = new Originator(old);
    Memento * pMemento = pOrigin->CreateMemento();
    cout<< *(pOrigin->GetState())<<endl;
    delete pOrigin;
    
    Originator * pNew = new Originator;
    pNew->SetMemento(pMemento);
    cout<< *(pNew->GetState())<<endl;
    delete pNew;
    
    delete pMemento;
    return 0;
}

 

posted @ 2014-08-22 14:02  庚武  Views(176)  Comments(0)    收藏  举报