#ifndef STATE_H #define STATE_H /////////////////////////////////////////////////////////////// // state2.h - defines states in terms of the events // // that trigger transitions to another state // // // // ver 1.0 Adds hooks for new state // // Language: Visual C++, ver 5.0 // // Platform: Micron Dual Pentium 200, NT 4.0 // // Application: Design Patterns - property pattern, Su98 // // Author: Jim Fawcett, CST 2-187, (314) 443-3948 // // fawcett@neptune.syr.edu // /////////////////////////////////////////////////////////////// #include #include using namespace std; // an extensible enumeration of states const int numStates = 5; const int onFF = 0; const int goUp = 1; const int onSF = 2; const int goDn = 3; const int newS = 4; class ElevBase { public: static ElevBase* getRegistered(int n) { if(n<0 || numStates<=n) { cout << " unknown state\n\n"; exit(1); } return registry[n]; } virtual ElevBase* upButton() { return newEvent(); } virtual ElevBase* dnButton() { return newEvent(); } virtual ElevBase* arrived() { return newEvent(); } virtual ElevBase* newEvent() { return this; } // this is a hook to add in new events protected: static vector registry; // shared by all elevator states }; template class ElevState : public ElevBase { public: ElevBase* makeState(int s) { if(s<0) { cout << " not a valid state\n"; exit(1); } ElevBase* pElevBase; return (pElevBase = registry[s] = new DerivedState); } }; // /////////////////////////////////////////////////////////////// // property classes // /////////////////////////////////////////////////////////////// //----< on the first floor >----------------------------------- class onFirstFloor : public ElevState { public: ~onFirstFloor() { delete registry[onFF]; } ElevBase* upButton() { cout << " going up\n"; return registry[goUp]; } }; //----< going up to second floor >----------------------------- class goingUp : public ElevState { public: ~goingUp() { delete registry[goUp]; } ElevBase* arrived() { cout << " arrived on second floor\n"; return registry[onSF]; } }; //----< on the second floor >---------------------------------- class onSecondFloor : public ElevState { public: ~onSecondFloor() { delete registry[onSF]; } ElevBase* dnButton() { cout << " going down\n"; return registry[goDn]; } }; //----< going down to first floor >---------------------------- class goingDown : public ElevState { public: ~goingDown() { delete registry[goDn]; } ElevBase* arrived() { cout << " arrived on first floor\n"; return registry[onFF]; } }; #endif