开发者

What is the best design pattern to register data "chunks"?

开发者 https://www.devze.com 2023-03-29 02:17 出处:网络
I have a library which can save/load on disk \"chunks\" which are POD structs with constant size and unique static CHUNK_ID field. So load looks somethink like this.

I have a library which can save/load on disk "chunks" which are POD structs with constant size and unique static CHUNK_ID field. So load looks somethink like this.

void Load(int docId, char* ptr, int type, size_t& size)...

If you want to add new chunk you just add struct with new CHUNK_ID and use Save Load functions to it.

What I want is to force all "chunks" to have functions like PrintHumanReadable, CompareThisTypeOfChunk etc(开发者_开发技巧Ideally program should not compile without such functions). Also I want to mark/register/enumerate all chunk-structs.

I have a few ideas but all of them have problems.

  1. Create base class with pure virtual functions PrintHumanReadable, CompareThisTypeOfChunk. Problem:breaks pod type and requires library rewriting.
  2. Implement factory which creates chunk struct from CHUNK_ID. Problem: compiles when I add new chunk without required functions.

Could you recomend elegant design solution for my problem?


Implement a simple code generator. You can use something like Mako or Cheetah (both Python libraries). Make a text file containing all the class names, then have the generator build the factory method and a series of methods which aren't really used but which refer to the desired methods in all the classes. This will also make it straightforward to enumerate the classes (again, using generated code).


The proper design pattern for this is called "use Boost.Serialization". It's really the best tool for writing objects to a format and then reading them back later. It can write in text, binary, and even XML formats (and others if you write a proper stream for them). It's can be non-intrusive, so you don't need to modify the objects to serialize them. And so forth.

Once you're using the proper tool for this job, you can then use whatever class hierarchy or other method you like to ensure that the proper functions for an object exist.

If you can't/won't use Boost.Serialization, then you're pretty much stuck with a runtime solution. And since the solution is runtime rather than compile time, there's no way to ensure at compile time that any particular chunk ID has the requisite functions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号