Visitor
Last updated
Last updated
Visitor is a behavioral design pattern that lets you separate algorithms from the objects on which they operate.
The Visitor pattern is a behavioral design pattern that allows you to add new operations to a set of classes without modifying those classes.
It achieves this by separating the operation from the object structure on which it operates.
In JavaScript, you can implement the Visitor pattern using a combination of functions and object-oriented principles.
The Visitor design pattern allows you to separate algorithms from the objects on which they operate.
It's useful when you have a set of classes with different interfaces, and you want to perform some operation on each object in a structure without altering the classes themselves.
In this example:
We have two element classes: Circle
and Square
, both with an accept
method that takes a visitor as an argument.
We define a Visitor
interface with visit methods for each type of element.
Then, we implement a concrete visitor, AreaVisitor
, which calculates the area of each shape it visits.
Finally, we have the client code that creates instances of shapes and applies the visitor to each shape.
This way, the visitor pattern allows us to define new operations (like calculating area) without modifying the shape classes themselves.