状态模式如下:
#include <boost/shared_ptr.hpp>
#include <iostream>
class State
{
public:
virtual void handle(const std::string &arg) = 0;
};
using StatePtr = boost::shared_ptr<State>;
class Context
{
public:
void setState(StatePtr state)
{
mState = state;
}
void request(const std::string &arg)
{
mState->handle(arg);
}
private:
StatePtr mState;
};
using ContextPtr = boost::shared_ptr<Context>;
class StateA : public State
{
public:
void handle(const std::string &arg)
{
std::cout << "StateA hanlde: " << arg << std::endl;
}
};
class StateB : public State
{
public:
void handle(const std::string &arg)
{
std::cout << "StateB hanlde: " << arg << std::endl;
}
};
int main()
{
StatePtr stateA(new StateA);
StatePtr stateB(new StateB);
ContextPtr context(new Context);
context->setState(stateA);
context->request("HHH");
context->setState(stateB);
context->request("KKK");
return 0;
}