c++ - Factory methods in derived classes -
i have 2 kinds of messages: messagea
, messageb
, both derived abstract class imessage
containing pure virtual method std::string tostring()
. can convert each message string representation pointer base class. that's fine. however, need somehow construct message (concrete type of message) string, example: messagea* msg = [something].fromstring( str )
. null if given string isn't suitable construction of messagea
. can see 2 approaches task:
a) messagefactory
dynamic_cast
class messagefactory { imessage* fromstring( const std::string& str ); }; ... messagefactory mf; messagea* msg = dynamic_cast< messagea* >( mf.fromstring( str ) ); if ( msg ) { ... }
however, uses dynamic_cast avoid.
b) factory method in each derived class
static messagea* fromstring( const std::string& str ) { return stringisok( str ) ? new messagea() : null; }
is there better solution? should change in general design? thank you.
update
sometime know kind of message should string, i.e.
void sendrequest() { ... std::string response; messagea* msg = fromstring( response ); // here should check if string valid messagea }
but sometime don't know come me:
void processmessage( const std::string& str ) { imessage* msg = fromstring( str ); if ( msg ) { messagea* msga = dynamic_cast< messagea* >( msg ); if ( msga ) ... } }
you make classes derived imessage
register (or rather specific factory) messagefactory
class statically @ program start. can achieved using static instance. imessage
interface needs have pure virtual method canconstructfrom(string&)
such when string comes in, pass messagefactory
, factory find out of derived classes can constructed string , instantiate correct one.
Comments
Post a Comment