Question

Let's say in my program I have a class called Robot that inherits from some other class.

Until now I have some methods inside Robot like addPart or getCost. Now I'm asked to add a new module of functionality to it (a few methods that use it's parts) but they explicitly ask the new module to be added with little to no impact to the current class.

I thought a Visitor could solve this but the thing is I won't be applying the pattern to a hierarchy. Is this a correct thing to do? (as you can see my Robot is part of a composite)

enter image description here

Was it helpful?

Solution

Fundamentally, I agree with your approach. You have successfully identified an approach that allows you to extend Robot (a parts composite) without having to actually modify the Robot class. The only changes I would make are the following:

I would introduce a new interface named something like IPartsComposite that would define the Accept method. This interface would be implemented by Robot since it is composed of Part instances.

The base Visitor would be a base generic class or interface i.e.Visitor<T>. This type would define a single method Visit(T). Then, in your case, you would have three concrete implementations of Visitor<IPartsComposite>.

  • PartsVisitorService
  • PartsVisitorCosts
  • PartsVisitorProduction

In each of these concrete classes you would implement Visit(IPartsComposite).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top