Question

This is a pretty abstract question, and I'm not necessarily looking for an answer or implementation, but rather some direction in terms of what approach I might use or material I might read.

Essentially, I am creating a storage scheme for certain data in many different forms, one of the being XML. When I load saved data from an XML file, I want to create user objects from the XML data.

I have an attribute within the XML hierarchy that provides a definition linked to the type of object that will be created; however, there are several different implementations of each type of object and I want to dynamically choose which object to create at runtime based on the elements nodes they provide and not have the user or anyone reading the XML worry or know about that.

As a result, my routine to parse the XML data has three steps:

(1) Parse all of the XML elements and save them as local variables

(2) Depending on which variables we gathered, instantiate the appropriate object

(3) Populate the object with the data

So, as a more concrete breakdown, my code ends up looking something like this (pseudocode, program written in C#):

// Object we're creating
GenericType object;

// Variables declarations
DURATION = "duration"
duration = 0;
...

// Step 1: Parse XML elements
switch(element.name)
{
  case element.name = DURATION:
    duration = element.value;
  case ...
}

// Step 2: Decide which object to instantiate, based on which variables were collected
// (variable analysis omitted for succinctness)
if(meetsRequirementsForObjectFoo())
  object = new Foo();
if(meetsRequirementsForObjectFooBar())
  object = new FooBar();
...

// Step 3: Populate object with data
Foo.setDuration(duration);
...

My question is what options/solutions do I have in terms of abstracting this data and eliminating some of the repetitiveness of this process? In the end, I'm basically creating a new user object based entirely off of the elements in the XML file; the issue is that I don't know which object I want to create until I've essentially read all of the data.

I would appreciate any help or references to existing design ideas/patterns that might be useful!

Was it helpful?

Solution

This would be a great candidate for the Factory Design Pattern. You could create a Factory that takes the XML as input (or the parsed variables, either way), and them decides which object to return based on that input, assuming the objects are all programmed to a similar interface. Otherwise, deserializing the XML to a class that matches the XML structure might be easiest and involve much less effort. See Deserializing XML to Objects in C# for more details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top