Dan S
Dan S

Reputation: 365

Can't figure out the correct approach (pattern...)

I have a problem and I'm having trouble finding the optimal aproach to it. A colleague recommended the Visitor pattern but I'm not sure if what I want can be done using Visitor. Even if it can be done there are some serious issues about clarity if I use that approach.

I'm trying to serialize / deserialize settings and finding that I need to add the same helper methods to a number of classes (bad). I'd prefer to move these helpers out of the classes I'm putting them in (which should have no code dealing with serialization / deserialization but am unsure how to factor it out) and into a centralized spot.

Currently I'm trying to get / set parameters on objects (buttons, other menu components, ...) which are contained in parent menu classes. I don't actually want these parent classes to have helper methods (both because it is causing code duplication across the parent classes and because the parent classes shouldn't "care" or "know" about these serialization / deserialization details)

The easiest way (of course) would be to have centralized methods that take a "void *" pointer. That aproach would be easy to read but (owing to the "void *") a bit dirty. The "void *" would be a reference to each of the parent (menu) classes I need to work on.

Given that I have m things that I have to get parameters to and from (and I can only access them through the n parent menu classes), and the parameter lists can be different... can I really use Visitor for this? Is it the proper pattern to use?

Upvotes: 2

Views: 94

Answers (2)

Fuhrmanator
Fuhrmanator

Reputation: 12882

Sounds like visitor fits the problem description, but it can be a bear to implement.

Assuming GUIElement is part of the hierarchy of objects you want to serialize, Manager figures how how to traverse those elements for the serialization order, and the Visitor class does the work of serializing, here's how I would see the dynamics of it based on your description:

Visitor sequence diagram

Diagram created here.

Upvotes: 0

Abhishek Bansal
Abhishek Bansal

Reputation: 5335

Visitor is definitely way to go. Using Visitor you can extend the functionality of class without having to modify it. The term "Visitor" apparently a misnomer and it has nothing to do with pattern, In-fact it is a very powerful pattern as it allows you to extend class from outside.
See this When should I use the Visitor Design Pattern?

Upvotes: 1

Related Questions