Design Mode - (Memento) without destruction of the package, a class status information in the capture and recovery based on this information.

Source code for the following: Design Solutions for fine pattern -GoF 23 design patterns to achieve desorption and C ++ source code

//Memento.h

#pragma once
#include<string>

class Memento;
class Originator{
public:
    typedef std::string State;
    Originator();
    virtual ~Originator();
    Originator(const State& st);
    Memento* createMemento();
    void SetMemento(Memento* men);
    void RestoreMemento(Memento* mt);
    State Getstate();
    void Setstate(const State&sdt);
    void PrintState();
protected:
private:
    Memento* _mt;
    State _st;
};

class Memento
{
public:
protected:
private:
    friend class Originator;
    typedef std::string state;
    Memento();
    virtual ~Memento();
    Memento(const state &sdt);
    void SetState(const state& sdt);
    state GetState();
    state _st;
};

//Memento.cpp

#include"Memento.h"
#include<iostream>
typedef std::string state;
Originator::Originator()
{
    _st = '\0';
    _mt = 0;
}
Originator::Originator(const state & sdt)
{
    _st = sdt;
    _mt = 0;
}
Originator::~Originator(){}
Memento* Originator::createMemento()
{
    return new Memento(_st);
}

void Originator::SetMemento(Memento* mem)
{

}
state Originator::Getstate()
{
    return _st;
}

void Originator::Setstate(const state&sdt)
{
    _st = sdt;
}

void Originator::PrintState()
{
    std::cout << this->_st << "...." << std::endl;
}

void Originator::RestoreMemento(Memento* mn)
{
    this->_st = mn->GetState();
}

Memento::Memento(){}
Memento::~Memento(){}
Memento::Memento(const state& sdt)
{
    _st = sdt;
}

state Memento::GetState()
{
    return _st;
}

void Memento::SetState(const state& sdt)
{
    _st = sdt;
}

//main.cpp

#include"Memento.h"
#include<iostream>
#include<string>

int main(int args, char* argv)
{
    Originator* o = new Originator();
    o->Setstate("Old");
    o->PrintState();
    Memento* m = o->createMemento();
    o->Setstate("New");
    o->PrintState();
    o->RestoreMemento(m);
    o->PrintState();
    getchar();
    return 0;
}

Guess you like

Origin www.cnblogs.com/fourmi/p/12083677.html