状态模式,可以很好的解决掉if else或者switch case判断,使用g++ state.cpp statemain.cpp -o microwaveoven
在Linux下编译即可执行microwaveoven查看结果
state.h
/*
@brief: 微波炉状态以及动作切换,三个状态:开门,关门,加热
四个动作:开门,关门,开始加热,停止加热
@author: njit-sam
@date: 2023.10.19
*/
#ifndef _STATE_H_
#define _STATE_H_
#include <iostream>
using namespace std;
class stateBase
{
public:
virtual bool openDoor() = 0;
virtual bool closeDoor() = 0;
virtual bool start() = 0;
virtual bool stop() = 0;
};
class doorOpen : public stateBase
{
public:
bool openDoor();
bool closeDoor();
bool start();
bool stop();
};
class doorClosed : public stateBase
{
public:
bool openDoor();
bool closeDoor();
bool start();
bool stop();
};
class heating : public stateBase
{
public:
bool openDoor();
bool closeDoor();
bool start();
bool stop();
};
class microWaveOven
{
public:
microWaveOven()
{
pStateOpen = new doorOpen();
pStateClose = new doorClosed();
pStateHeating = new heating();
pState = pStateClose;
}
~microWaveOven()
{
delete pStateOpen;
delete pStateClose;
delete pStateHeating;
}
void openDoor();
void closeDoor();
void start();
void stop();
private:
stateBase* pState;
stateBase* pStateOpen;
stateBase* pStateClose;
stateBase* pStateHeating;
};
#endif
state.cpp
/*
@brief: 微波炉状态以及动作切换,三个状态:开门,关门,加热
四个动作:开门,关门,开始加热,停止加热
@author: njit-sam
@date: 2023.10.19
*/
#include"state.h"
bool doorOpen::openDoor()
{
cout<<"doorOpen: already open"<<endl;
return false;
}
bool doorOpen::closeDoor()
{
cout<<"doorOpen: close"<<endl;
return true;
}
bool doorOpen::start()
{
cout<<"doorOpen: cant heat"<<endl;
return false;
}
bool doorOpen::stop()
{
cout<<"doorOpen: cant stop"<<endl;
return false;
}
bool doorClosed::openDoor()
{
cout<<"doorClosed: open"<<endl;
return true;
}
bool doorClosed::closeDoor()
{
cout<<"doorClosed: already close"<<endl;
return false;
}
bool doorClosed::start()
{
cout<<"doorClosed: start heat"<<endl;
return true;
}
bool doorClosed::stop()
{
cout<<"doorClosed: cant stop"<<endl;
return false;
}
bool heating::openDoor()
{
cout<<"heating: cant open"<<endl;
return false;
}
bool heating::closeDoor()
{
cout<<"heating: cant close"<<endl;
return false;
}
bool heating::start()
{
cout<<"heating: already start"<<endl;
return false;
}
bool heating::stop()
{
cout<<"heating : stop"<<endl;
return true;
}
void microWaveOven::openDoor()
{
if(pState->openDoor() == true)
pState = pStateOpen;
}
void microWaveOven::closeDoor()
{
if(pState->closeDoor() == true)
pState = pStateClose;
}
void microWaveOven::start()
{
if(pState->start() == true)
pState = pStateHeating;
}
void microWaveOven::stop()
{
if(pState->stop() == true)
pState = pStateClose;
}
main.cpp
#include<stdio.h>
#include"state.h"
int main()
{
microWaveOven mw0;
mw0.openDoor();
mw0.start();
return 0;
}