Skip to content
Advertisement

Best way to serialize composite – (design pattern)

I have following java code that is implementation of Composite Design pattern:

JavaScript

There are 2 possible composite roots here (CompositeA and CompositeB) and one leaf component (Leaf).

Here I define DTOs that will hold serialized data:

JavaScript

Now if I use visitor pattern for serialization, I get something like this:

JavaScript

and if I use instanceof this is the code that does the same thing:

JavaScript

I guess also that visitor is preferred here because when we add new Component, we are required to implement Object accept(ComponentVisitor visitor) method also – so we cannot forget that we need a code for serialization of this new component. If we do the same when we use instanceof we would possibly forget to add it to that check.

Now – my question is – is there any way that we can get rid of that ugly Object return type in Object accept(ComponentVisitor visitor) method signature? The only other option that comes to my mind is to use some marker interface (eg. interface SerializedComponent {}) and then have all serializer classes implement that empty interface like this class WholeCompositeASerialized implements SerializedComponent but it still does not seem right.

Advertisement

Answer

I think the proper way could be to use generics here.

e.g. https://onlinegdb.com/r1m5Eg4DP

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement