In the state model of design pattern, how does one handle the case where the states have to save information? Let me give you some background: I am writing a driver that sends JPEGs and XML files to the hardware. One of the routines of the driver receives chunks of data (64 k) . The job of this routine is to save this data until it receives a complete JPEG or an XML, and then send it across to the HW. The problem that I face is sharing the data across the different states. I have a single buffer that is shared across all the states. Moreover other information like size of the JPEGs and XMLs need to be saved across the states. I am attaching the code for ur refernce: Code: class start_state : public State { public: HPBool ProcessData(Machine *pMachine, HPCByte *pBuff, HPDword cbBuff, HPUInt& bytesWritten); void setNextState(State *pState); private: int ExtractLength(HPCByte *pBuff); state DetermineState(HPCByte *pBuff); int m_len; }; class jpg_state : public State { public: HPBool ProcessData(Machine *pMachine, HPCByte *pBuff, HPDword cbBuff, HPUInt& bytesWritten); void setNextState(State *pState); }; class xml_state : public State { public: HPBool ProcessData(Machine *pMachine, HPCByte *pBuff, HPDword cbBuff, HPUInt& bytesWritten); void setNextState(State *pState); }; class send_state : public State { public: HPBool ProcessData(Machine *pMachine, HPCByte *pBuff, HPDword cbBuff, HPUInt& bytesWritten); void setNextState(State *pState); }; class reset_state : public State { public: HPBool ProcessData(Machine *pMachine, HPCByte *pBuff, HPDword cbBuff, HPUInt& bytesWritten); void setNextState(State *pState); }; class Machine { class State *current; public: Machine(); void setCurrentState(class State *s) { current = s; } HPBool Process(HPCByte *pBuff, HPDword cbBuff, HPUInt& bytesWritten); }; class State { protected: static int m_file_size; static int m_rcxed_size; Machine *pMachine; static MemoryBuffer fBuffer; public: virtual HPBool ProcessData(Machine *pMachine, HPCByte *pBuff, HPDword cbBuff, HPUInt& bytesWritten) = 0; virtual void setNextState() = 0; };
Only what is needed to make the state machine work. So it is dependent on the design of your state machine. If for example state 1 is called when a variable is clear and state 5 is called when that variable is set, then in effect no extra information is needed. But if state 1 is called regardless of the state of that variable (and of course is dependent on the contents of that variable) then there needs to be additional information somewhere that indicates whether or not that variable is set.