jeudi 16 mars 2017

Design pattern for method returning different types/classes

This is a question for the Object Design Pattern specialists.

Let's assume I have a Parser class that is in charge of reading/parsing a stream of data (that carry information packets of different types). Each of these packets carry a different type of information, so ideally I would have a class for each type of packet (PacketTypeA, PacketTypeB, ... each one with its own interface).

class Parser {

public:

    /* ctor */
    /* dtor */


   void read_packet(/* arguments */);

   // methods...
private:
   // more methods...
}

The method Parser::read_packet would then go through the stream and return a class (or pointer or reference to a class) to the appropriate packet type.

Would you use void pointers for this? How about a generic class (PacketBasicInterface) that would provide a common (partial) interface to query about the type of packet (so that any decision could then be made at runtime)?

// Pure virtual (abstract) class to provide a common (and partial) interface
class PacketBasicInterface {
public:

    std::string whoAmI() const = 0;
    bool amIofType(const std::string& type) const = 0;

}

// Class to access data of type A packet
class PacketTypeA : public PacketBasicInterface {

public:
    // methodA_1()
    // methodA_2(), ...
}

// Class to access data of type A packet
class PacketTypeB : public PacketBasicInterface {

public:
    // methodB_1()
    // methodB_2(), ...
}

Any thought or feedback would be very much appreciated!

Many thanks!

Aucun commentaire:

Enregistrer un commentaire