I have something like the following in the title
class MsgBase { public: unsigned int getMsgType() const { return type_; } ... private: enum Types { MSG_DERIVED_1, MSG_DERIVED_2, ... MSG_DERIVED_N }; unsigned int type_; ... }; class MsgDerived1 : public MsgBase { ... }; class MsgDerived2 : public MsgBase { ... }; ... class MsgDerivedN : public MsgBase { ... };
and used as
MsgBase msgHeader; // peeks into the input stream to grab the // base class that has the derived message type // non-destructively inputStream.deserializePeek( msgHeader ); unsigned int msgType = msgHeader.getMsgType(); MsgDerived1 msgDerived1; MsgDerived2 msgDerived2; ... MsgDerivedN msgDerivedN; switch( msgType ) { case MSG_DERIVED_1: // fills out msgDerived1 from the inputStream // destructively inputStream.deserialize( msgDerived1 ); /* do MsgDerived1 processing */ break; case MSG_DERIVED_2: inputStream.deserialize( msgDerived2 ); /* do MsgDerived1 processing */ break; ... case MSG_DERIVED_N: inputStream.deserialize( msgDerivedN ); /* do MsgDerived1 processing */ break; }
This seems like a type of situation that would be fairly common and well suited for refactoring. What would be the best way to apply design patterns (or a basic redesign of a C ++ language) to reorganize this code?
I read that the command template is usually used for refactoring operators, but this seems to be applicable only when choosing between algorithms to complete a task. Is this a place to apply a factory pattern or an abstract factory (I am not very familiar too)? Double dispatch?
I tried to eliminate as much of the irrelevant context as possible, but if I missed something important, just let me know and I will edit it to include it. Also, I couldn't find anything like that, but if it's a duplicate, just redirect me to the appropriate SO question.
c ++ design-patterns refactoring
bpw1621
source share