定义一个状态基类state,然后继承出来两个状态:company和home,通过stateManger类去管理当前状态,状态切换。这个模式感觉像是把一个过程的状态切开分为很多个小段,各个状态只通过一个管理类去维护。
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
class state {
public:
virtual state* getState() = 0;
virtual string getStateName() = 0;
};
class stateHome : public state {
public:
static stateHome* getInstance() {
static stateHome* instance = new stateHome();
return instance;
}
virtual string getStateName() { return "Home"; };
virtual state* getState() {
return getInstance();
}
};
class stateCompany : public state {
public:
static stateCompany* getInstance() {
static stateCompany* instance = new stateCompany();
return instance;
}
virtual string getStateName() { return "Company"; };
virtual state *getState() { return getInstance(); }
};
class stateManager {
public:
state* getState() { return stateCurent; }
void setState(state* st) { stateCurent = st; }
private:
state* stateCurent;
};
int main() {
stateManager *mstateManager = new stateManager();
mstateManager->setState(stateCompany::getInstance());
cout << mstateManager->getState()->getStateName() << endl;
mstateManager->setState(stateHome::getInstance());
cout << mstateManager->getState()->getStateName() << endl;
}
|