[SOLVED] How to deserialize derived class in Qt



  • Hi everyone, I have a problem with serialize/deserialize some Shape objects in my project, with serialize, I come up with a solution quite satisfied, using virtual method:

    @
    enum ShapeType{CIRCLE, SQUARE, QUAD};

    class Shape(){
    public:
    Shape(const QVector2D &pos):m_pos(pos){}
    void serialize(QDataStream &stream){
    stream << type() << m_pos;
    doSerialize(stream);
    }

    private:
    virtual ShapeType type()=0;
    virtual void doSerialize(QDataStream &stream){}

    private:
    QVector2D m_pos;
    }

    QDataStream& operator<<(QDataStream &stream, const Shape &shape){
    shape.serialize(stream);
    return stream;
    }

    class Circle: public Shape{
    public:
    Circle(QVector2D pos, float radius):Shape(pos), m_radius(radius){}

    private:
    virtual ShapeType type(){return CIRCLE;}
    virtual void doSerialize(QDataStream &stream){
    stream<<m_radius;
    }

    private:
    float m_radius;
    }
    @

    But when deserializing, I have to use this switch statement to create the derived object:
    @
    Shape *deserialize(QDataStream &stream){
    ShapeType type;
    stream >> type;
    QVector2D pos;
    stream >> pos;
    switch(type){
    case CIRCLE:
    {
    float radius;
    stream >> radius;
    return new Circle(pos, radius);
    }
    break;
    }
    return 0;
    }
    @

    I heard that the above switch statement is antipattern and cumbersome under maintaining, so how to eliminate the switch statement to create object which doesn't need the type() to specify derived class?
    Is there any Qt's way about this?

    Any suggestion would be appreciated.


  • Moderators

    That seems like a classic case for the "factory pattern":http://www.oodesign.com/factory-pattern.html

    Basically you register a factory object for each possible type somewhere during the setup of your application. When you want to deserialize you get the type from the stream, ask each factory which one can produce objects of that type and then have the factory create an object for you from the stream.



  • Thanks Tobias Hunger for your help, the factory pattern seems to be the right solution.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.