2

Eric Gamma's Design Patterns book explains that a composite structure may declare operations: enter image description here

Such operations are propagated recursively by non-leaf operators.

On the other hand, we may get the same result by using a visitor design pattern to create visitors that visit the composite structure and do the operation.

So, is there any reason why one would chose to add an operation in the composite rather than creating a new visitor for each desired operation? Or vice versa?

alex_noname
  • 26,459
  • 5
  • 69
  • 86

1 Answers1

2

I will not describe the meaning of the patterns, there are already many such excellent descriptions. But I will say that these patterns complement each other. The visitor allows us to add new operations without changing the classes of objects on which these operations can be performed, but if we can change these classes we can add a new operation to them without using the visitor, it all depends on the context.

Sometimes at the development stage we cannot predict what operations will be performed on the composite objects, but we can provide the possibility of adding such functionality in the future by adding the accept() method to the interface of the composite object that takes the visitor's interface and calls its visit() method for the current object.

alex_noname
  • 26,459
  • 5
  • 69
  • 86