Home >Backend Development >C++ >How to Elegantly Serialize Classes to a Stream in C Using the Factory Pattern?
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 &is) { int id; is >> id; switch(id) { case EXAMPLE_ID: return new ExampleClass(is); //... } } void serialize(ostream &os) { os << getClassID(); serializeMe(os); } protected: int getClassID()=0; void serializeMe(ostream &os)=0; };
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>
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!