Visitor

Separate algorithms from objects they operate on

Overview

Visitor allows you to separate algorithms from the objects on which they operate. It's used when you have a complex object structure and you want to perform operations on these objects depending on their concrete classes.

Code Example

java
1public interface ItemElement { int accept(ShoppingCartVisitor visitor); }
2public interface ShoppingCartVisitor {
3    int visit(Book book);
4    int visit(Fruit fruit);
5}
6// Concrete ItemElements implement accept by calling visitor.visit(this)

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In
Visitor - Behavioral Patterns | LLD | Revise Algo