I'm trying to come up with a good design for converting a set of different objects into a common object. Basically, I receive one (of many slightly different) complex object from system A, and must convert it into a simpler object for system B.
The objects I'm converting from all inherit from the same base class, so part of the conversion is always the same. But in every case, the conversion does involve something very specific to the type of the object I'm converting. It could be a RPC, an HTTP fetch, a database lookup, or something entirely different.
I'm looking at the Template method and the Strategy patterns. But neither seems like a perfect fit. The problem is that the method/strategy to use is tied to the type of object being converted and so isn't interchangeable.
This is a sketch of what I'm thinking about doing:
class FooConverter {
Map<String, FooConverter> converters;
Foo convert(Bar bar) {
Foo foo = ...; // Common part of the conversion.
FooConverter c = converters.get(bar.getType(), foo);
c.finishConversion(bar, foo);
return foo;
}
}
What annoys me is that FooConverter
must define an additional conversion method that takes the partially converted object as a parameter. So I end up with a mix of a Strategy (since all the converters implement the same interface) and Template method (since the common part of the conversion is shared by all the converter). Is there a better way?