At the moment I am working on a message class in C++ for data communication, e.g. over a serial port. For this question let's say I have two different messages (I do have more), e.g. a gyroscope- and a acceleration message both with calibration data and sensor values. Since I am an engineer who learned C++ for himself I had a look at my favorite C++ book and figured out that it might be useful to use a factory pattern for the message.
So a simplified version of my header file looks like this:
#ifndef MESSAGE_H
#define MESSAGE_H
#include <cstddef>
class message
{
public:
/**
* \brief ~message:
* Virtual destructor of the class message.
*/
virtual ~message();
/**
* \brief getMessage:
* Creates a message (with new).
*
* \param[in] size Size of the dataArray.
* \param[in] data Bytearray of the message.
*
* \return If messagetype in the Array data eqal to 0 => new GyroMessage.
* If messagetype in the Array data eqal to 1 => new AccelMessage.
* Else => new NotValidMessage.
*
*/
static message* getMessage(size_t size, char* data);
protected:
/**
* \brief message:
* Default konstructor of the class message.
*
* \param[in] size Size of the dataArray.
* \param[in] data Bytearray of the message.
*
*/
message(size_t size, char* data);
/// Size of the dataArray.
int size;
/// Bytearray of the message.
char* dataArray;
/// Type of message.
char messagetype;
};
#endif // MESSAGE_H
The clases GyroMessage, AccelMessage and NotValidMessage are child classes of message. There are two things I do not like about this pattern:
First: If I want to add a new message, it is now enough to add a new class which is inherited form message, you have to add another if statement is in the static function getMessage.
Second: If I want to use the data e.g. from the GyroMessage, I have to reinterpret_cast the message.
Is there a better pattern that I could use for this purpose?