mardi 8 septembre 2015

Object creation chaining pattern

I have an XML file with complex structure. Following is just a small sample.

    <MainTag>
        <Tag1 name="">
            <SubTag1_1 msgType="">
            <SubTag1_2 storeId="abc" abc=""/>
            </Tag1>
            <Tag2 msgType="">
                <SubTag2_1 name="" cap="" value="#"/>
                <SubTag2_2=""/>
            </Tag2> 
        </Tag1>

        <Tag3 name="">
            <SubTag3>
                <SubTag3_1 msgType="A" value="1">
                    <SubSubTag3 name="" xml="" sap="" time_delta="0" time_absolute="2"/>
                    <SubSubTag3 name="" xml="" sap="" type="transmit" time_delta="5" time_absolute="2"/>
                </SubTag3_1 >
                <SubTag3_2 msgType="" value="1">
                    <SubSubTag3 name="" xml="" sap="" type="receive" time_delta="0" time_absolute="2"/>
          </SubTag3_2>
      </SubTag3>
   </Tag3>
</MainTag>

I have to create the above XML file multiple times for different set of data. Instead of having a single class to take all the data and write the XML file, I have created a kind of object graph. Each main Tag is represented by a class. For example

Class MainTag will have a reference of classes Tag1 and Tag3. Tag1 class will have reference to sub classes SubTag1, Tag2 etc. Further, each class implements IXmlSerializable interface which makes writing the XML file pretty easy and nicely divided. Dividing the classes also helps if the XML structure is changed.

Questions:

1) Is the approach correct to divide the XML structure into a set of classes ?

2) Since I have a lot of classes, I have to initialize all the class structure (object graph). Once the data (that i want to insert in the xml) is ready, I want to start the initialization of whole object graph. Once initialization is done, I just want to write the XML using IXmlSerializable interface .Is there any design pattern for the kind of object initialization I am using ? Currently, I am just doing the following. This looks strange.

class MainTag: XmlBase
{
    List<Tag1> Tag1List{ get; set; }
    Tag1 t;

    public MainTag() : base()
    {
       t = new Tag1();
       //Do processing and populate the properties of MainTag
    }
}

class Tag1 : XmlBase
{
  List<SubTag1_1> subtags;
  SubTag1_1 s;

  public Tag1()
  {
      s = new SubTag1_1();
      //Do processing and populate the properties of Tag1
  }
}

Aucun commentaire:

Enregistrer un commentaire