Pergunta

I have a tree data structure where each node describes how to use its child nodes, and this tree is stored in a standard data format - XML for now. However, there are a large number of different kinds of nodes, and I shouldn't have to update the core code that reads in the XML and converts it to software objects every time I want to add a new node type.

My solution is to use an interface in the core reader code. Each node object will have an associated reader object that implements the interface, and when the core reader runs into a node X, it will go fetch X's associated reader object by name out of a global data structure that gets populated on program startup. The core reader will have the specific reader object read in the node; the specific reader object can likewise easily call back into the general reader code. If someone authors their own node types and readers (i.e. dynamic library), they could update the global table and presto, everything keeps working.

The issue is that I don't know if there is a more canonical solution to this problem. Looking up objects by string/id/whatever seems fishy, but I can't see another way to convert from data to code. I'm also wondering if having the algorithms that run on this data structure (once it's loaded into software) implement a similar mechanism would also be a good idea; new nodes could update existing algorithms without needing to rewrite them.

Update to clarify that I'm converting from XML to software object, not parsing the syntax of XML itself.

Foi útil?

Solução

Yeah this seems like a pretty standard way of doing things.

Check out how json.net allows you to add custom type serialisers for example

Licenciado em: CC-BY-SA com atribuição
scroll top