Pattern "Visitor" or a dynamic cast?

nightin_gale

I need good advise for my business logic!

I have such classs hierarchy:

Parent
- Child1 implements Parent
- Child2 implements Parent

Child1 has its own methods and fields as Child2 has its own.

I can write:

Parent p = new Child1();
( ( Child1 ) p ).getMethodInParent1

p = new Child2();
( ( Chuld2 ) p ).getMethodInParent2

But there are a lot of methods in Child1 and Child2. My main goal is using only one instance of Parent - p. And I want to ask you if it is good aproach of using dynamic cast everywhere in code?

I have read about Visitor pattern. Could it help me in my desire to avoid dynamic cast?

Sergey Kalinichenko

I want to ask you if it is good approach of using dynamic cast everywhere in code?

No, it is not. Using casts in general should be regarded as an exception, not as a rule. If your design is based on the need to cast everywhere, you should revisit your design before starting to code.

Could [the Visitor pattern] help me in my desire to avoid dynamic cast?

Yes, it can. However, you need to remember that introducing a Visitor Pattern in your code significantly increases the complexity of your code, so it needs to be very well justified.

I would try hard unifying the interfaces of Child1 and Child2 into the Parent, so that a simple polymorphism would be sufficient. If that does not work because the code must behave as virtual with respect to more than one object, I would use the visitor pattern.

Note: Visitor pattern has several limitations. One of them is that your class hierarchy should be reasonably fixed. If you plan to add new ChildXYZ implementations to your code, the Visitor pattern will be a liability, not an advantage, because it would make adding new classes harder.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related