samedi 28 avril 2018

Design Pattern for converting objects to/from bytes

I have a class A that contains instances of several other Classes B, C and D as shown.

I want to convert Class A and its contents to an array of bytes and store them in a file. Later I want to read the byte array from the file and convert it back to an instance of Class A as shown here. I'm having trouble designing an elegant solution that converts back and forth between objects and byte arrays.

One solution I considered was creating a single converter class that can convert back and forth between all my objects and byte arrays :

public Converter{

   public static ClassA getInstance(byte[] b){...return new ClassA()}
   public byte[] getBytes(ClassA classA){...}

   public static ClassB getInstance(byte[] b){...return new ClassB()}
   public byte[] getBytes(ClassB classB){...}

}

This approach results in a very large class with a lot of methods.

Another approach is to make a "Converter class" for each class that I want to store in the file.

public ClassAConverter extends Converter<ClassA>{

   public ClassA getInstance(byte[] b){...return new ClassA()}
   public static byte[] getBytes(ClassA classA){...}

}

public ClassBConverter extends Converter<ClassB>{

   public ClassB getInstance(byte[] b){...return new ClassB()}
   public static byte[] getBytes(ClassB classB){...}

}

This design however seems to have the disadvantage of creating a large amount of classes.

I'm that aware that Java Serialization achieves most of what I've described here, but I'm looking for a more flexible and customized solution that also enables the file to be parsed by other independant programs.

Is there any design pattern that could help implement the conversion logic more elegantly?

Aucun commentaire:

Enregistrer un commentaire