Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integration of Serialization and Deserialization in Builder Design Pattern using C#

I am implementing the Builder Pattern in order to generate a set of objects. These objects then have to be serialized to XML and deserialized from XML.

I know how to perform the serialization and deserialization however I am unsure how to integrate it into the design pattern.

For example suppose my code uses the builder to create products foo and bar. My first thought is to put a serialize function on each one because each product knows what to serialize.

My next thought was to put the deserialization in the Director or the ConcreteBuilder.

What I don't like about this is that the serialization and deserialization functions will be in different places - one in the file for the declaration of the foo and bar objects and the other in the files for something else. I am worried that they might end up becoming out of sync with each other as I work on the product classes.

My final thought was for the Director or ConcreteBuilder to perform the serialization and deserialization. What I don't like about that is the products then have to know which builder was used or know who the Director is.

To clarify - there are two situations where a product can be created:

  1. User clicks on a button in the user interface
  2. User loads a XML project
like image 258
Andy Avatar asked May 19 '11 15:05

Andy


1 Answers

Can you not simply have a static serialize/deserialize class and create a generic method that can take any type of object? Isn't the pattern simply for building the objects? You can then serialize as you wish?

Something like:

public static string Serialize<T>(T data)
    {
       XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
       StringWriter sw = new StringWriter();
       xmlSerializer.Serialize(sw, data);
       return sw.ToString();

    }
like image 98
Darren Young Avatar answered Oct 03 '22 01:10

Darren Young