UML—状态图

来源:互联网 发布:西南财经大学网络教育 编辑:程序博客网 时间:2024/05/16 11:03

状态图如图:


代码:

#include<iostream>using namespace std;//定义状态变量,用不同整数表示不同状态const int OPENING = 1;const int OPEN = 2;const int CLOSING = 3;const int CLOSED = 4;class Motor{private:    int s;public:    void setS(int s1)    {        s=s1;    }    void getS()    {        switch(s)        {        case OPENING:        {            cout <<"motor up" << endl;            break;        }        case OPEN:        {            cout << "motor off" << endl;            break;        }        case CLOSING:        {            cout << "motor down" << endl;            break;        }        case CLOSED:        {            cout << "motor off" << endl;            break;        }        }    }};class Door{public:    Door():state(CLOSED) {};    void getState()    // 根据当前状态输出相应的字符串    {        switch(state)        {        case OPENING:        {            motor.setS(state);            motor.getS();            cout <<"OPENING" << endl;            break;        }        case OPEN:        {            motor.setS(state);            motor.getS();            cout << "OPEN" << endl;            break;        }        case CLOSING:        {            motor.setS(state);            motor.getS();            cout << "CLOSING" << endl;            break;        }        case CLOSED:        {            motor.setS(state);            motor.getS();            cout << "CLOSED" << endl;            break;        }        }    }    void depress()       // 发生depress事件时进行状态转换    {        if (state == CLOSED||state == CLOSING)   setState(OPENING);        else if (state == OPEN)   setState(CLOSING);    }    void doorOpen()     // 发生doorOpen事件时进行状态转换    {        if (state == OPENING)   setState(OPEN);    }    void doorClosed()    // 发生doorClosed事件时进行状态转换    {        if (state == CLOSING)   setState(CLOSED);    }private:    Motor motor;    int state;                 // 传输门当前状态    void setState(int state)   // 设置当前状态    {        this->state = state;    }};int main(){    Door aDoor;    aDoor.getState();   // CLOSED    aDoor.depress();    aDoor.getState();   // OPENING    aDoor.doorOpen();    aDoor.getState();   // OPEN    aDoor.depress();    aDoor.getState();   // CLOSING    aDoor.doorClosed();    aDoor.getState();   // CLOSED    return 0;}

运行结果:


0 0
原创粉丝点击