Visitor pattern: change object state?
Asked Answered
T

3

8

Is it acceptable that visitor change the state of object in which it operates? These kind of operation are not considered as anti patterns?

Tonsorial answered 30/12, 2015 at 23:45 Comment(3)
As visitor operates with object it can access any public methods and properties. So it is up to you to set required encapsulation of object. Visitor should be able both accessing read-only properties to display something or gather info as well as change object state by call of public method like MarkVisited() or Init(). It looks like payload for visitorSeyler
It's helpful when you don't have source code of the third party classes. You can declare methods in Visitor and add a common a operation, spanning across multiple related objectsPedestrian
Possible duplicate of Command Pattern vs. Visitor PatternHiga
I
6

It's completely fine to modify the objects that are visited.

Just make sure that your visitor class is named appropriately, so it is obvious that it has a side-effect.

Immuno answered 30/12, 2015 at 23:53 Comment(1)
An Example would be a visitor who visits every node (monster, tower, whatever) and raises their (I'm thinking of a game here) strength randomly between 25% to 50%. Thats a valid visitor who mutates what it visits.Continuator
R
3

As long as the visitor only uses the public interface and none of the interface methods allow the visitor to put the object in an invalid state. The visitor is free to change the state of the visited object.

Royo answered 30/12, 2015 at 23:54 Comment(0)
H
2

As the other answers have mentioned, there's no anti-pattern in mutating the object during its visit; but as with all mutable state, care must be taken in multi-threaded scenarios. Make sure that no other thread is mutating the object at the same time as the visitor, or else ensure proper synchronization.

Higa answered 31/12, 2015 at 0:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.