Is it acceptable that visitor change the state of object in which it operates? These kind of operation are not considered as anti patterns?
Visitor pattern: change object state?
Asked Answered
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 visitor –
Seyler
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 objects –
Pedestrian
Possible duplicate of Command Pattern vs. Visitor Pattern –
Higa
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.
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
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.
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.
© 2022 - 2024 — McMap. All rights reserved.