[说明]
传输门是传输系统中的重要装置。传输门具有 Open(打开)、Closed(关闭)、Opening(正在打开)、StayOpen(保持打开)、Closing(正在关闭)五种状态。触发传输门状态转 换的事件有 click、complete 和 timeout 三种。事件与其相应的状态转换如图 6-1 所示。
下面的[C++代码 1]与[C++代码 2]分别用两种不同的设计思路对传输门进行状态模拟, 请填补代码中的空缺。
[C++代码 1] const int CLOSED = 1; const int OPENING = 2; const int OPEN = 3; const int CLOSING = 4; const int STAYOPEN = 5; //定义状态变量,用不同整数表示不同状态class Door {
private: int state; //传输门当前状态 void setState(int state){ this->state = state; } //设置当前状态 public: Door():state(CLOSED){}; void getState(){ //根据当前状态输出相应的字符串 switch(state){ case OPENING: cout <<"OPENING" << endl; break; case CLOSED: cout << "CLOSED" << endl; break; case OPEN: cout << "OPEN" << endl; break; case CLOSING: cout << "CLOSING" << endl; break; case STAYOPEN: cout << "STAYOPEN" << endl; break; } } void click() { //发生click事件时进行状态转换 if ( state==CLOSED || state==CLOSING) setState(OPENING); else if ( state==STAYOPEN || state==OPENING) setState(CLOSING); else if ( state=OPEN ) setState(STAYOPEN); } void timeout(){ //发生timeout事件时进行状态转换 if (state == OPEN) setState(CLOSING); } void complete(){ //发生complete事件时进行状态转换 if (state == OPENING) setState(OPEN); else if (state == CLOSING) setState(CLOSED); } }; int main(){ Door aDoor; aDoor.getState(); aDoor.click(); aDoor.getState(); aDoor.complete(); aDoor.getState(); aDoor.click(); aDoor.getState(); aDoor.click(); aDoor.getState(); return 0; }[C++代码 2]
class Door { public: DoorState *CLOSED, *OPENING, *OPEN, *CLOSING, *STAYOPEN, *state; Door(); virtual ~Door(){ …… //释放申请的内存,此处代码省略}; void setState(DoorState *state) { this->state = state; } void getState(){ // 此处代码省略,本方法输出状态字符串, // 例如,当前状态为CLOSED时,输出字符串为“CLOSED” }; void click(); void timeout(); void complete(); }; Door::Door(){ CLOSED = new DoorClosed(this); OPENING = new DoorOpening(this); OPEN = new DoorOpen(this); CLOSING = new DoorClosing(this); STAYOPEN = new DoorStayOpen(this); state = CLOSED; } void Door::click(){ state->click();} void Door::timeout(){ state->timeout(); } void Door::complete(){ state->complete(); }class DoorState //定义一个抽象的状态,它是所有状态类的基类
{ protected: Door *door; public: DoorState(Door *door) { this->door = door; } virtual ~DoorState(void); virtual void click() {} virtual void complete() {} virtual void timeout() {} };class DoorClosed :public DoorState{ //定义一个基本的 Closed 状态
public: DoorClosed(Door *door):DoorState(door) {} virtual ~ DoorClosed (){} void click(); }; void DoorClosed::click() { door->setState(door->OPENING); } // 其它状态类的定义与实现代码省略int main(){
Door aDoor; aDoor.getState(); aDoor.click(); aDoor.getState(); aDoor.complete(); aDoor.getState(); aDoor.timeout(); aDoor.getState(); return 0; }