Home > Backend Development > C++ > How to Elegantly Serialize Classes to a Stream in C Using the Factory Pattern?

How to Elegantly Serialize Classes to a Stream in C Using the Factory Pattern?

Linda Hamilton
Release: 2024-10-29 02:45:29
Original
1001 people have browsed it

How to Elegantly Serialize Classes to a Stream in C   Using the Factory Pattern?

Serialization to a Stream for a Class Demystified

When faced with the need for object serialization in C , many resort to a familiar pattern that involves class ID-based switching:

<code class="cpp">class Serializable {
  public:
    static Serializable *deserialize(istream &amp;is) {
        int id;
        is >> id;
        switch(id) {
          case EXAMPLE_ID:
            return new ExampleClass(is);
          //...
        }
    }

    void serialize(ostream &amp;os) {
        os << getClassID();
        serializeMe(os);
    }

  protected:
    int getClassID()=0;
    void serializeMe(ostream &amp;os)=0;
};
Copy after login

While this approach may seem intuitive, it suffers from potential pitfalls:

The Factory Pattern Approach

A more elegant and extensible solution is to employ the factory pattern. Instead of relying on class IDs, a factory class creates objects based on a registered set of key-function pairs. The functions return instances of the corresponding classes.

<code class="cpp">template<typename K, typename T>
class Factory {
    typedef T *(*CreateObjectFunc)();
    std::map<K, CreateObjectFunc> mObjectCreator;

    template<typename S> 
    static T* createObject(){ 
        return new S(); 
    }

    template<typename S> 
    void registerClass(K id){ 
        mObjectCreator.insert( std::make_pair<K,CreateObjectFunc>(id, &createObject<S> ) ); 
    }

    T* createObject(K id){
        typename std::map<K, CreateObjectFunc>::iterator iter = mObjectCreator.find(id); 
        if (iter == mObjectCreator.end()){ 
            return NULL;
        }
        return ((*iter).second)();
    }
};</code>
Copy after login

In this implementation, each class of interest is registered with the factory, associating its class ID with a creation function. When an object is to be deserialized, the factory is queried for the corresponding class ID. If found, the creation function is invoked to instantiate the object.

The above is the detailed content of How to Elegantly Serialize Classes to a Stream in C Using the Factory Pattern?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template