The Wayback Machine - https://web.archive.org/web/20240930213040/https://www.geeksforgeeks.org/visitor-design-pattern/
Open In App

Visitor design pattern

Last Updated : 07 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Visitor design pattern is one of the behavioral design patterns. It is used when we have to perform an operation on a group of similar kind of Objects. With the help of visitor pattern, we can move the operational logic from the objects to another class. The visitor pattern consists of two parts:

  • a method called Visit() which is implemented by the visitor and is called for every element in the data structure
  • visitable classes providing Accept() methods that accept a visitor

UML Diagram Visitor design pattern

Visitor-Design-Pattern-Diagram

Design components

  • Client : The Client class is a consumer of the classes of the visitor design pattern. It has access to the data structure objects and can instruct them to accept a Visitor to perform the appropriate processing.
  • Visitor : This is an interface or an abstract class used to declare the visit operations for all the types of visitable classes.
  • ConcreteVisitor : For each type of visitor all the visit methods, declared in abstract visitor, must be implemented. Each Visitor will be responsible for different operations.
  • Visitable : This is an interface which declares the accept operation. This is the entry point which enables an object to be “visited” by the visitor object.
  • ConcreteVisitable : These classes implement the Visitable interface or class and defines the accept operation. The visitor object is passed to this object using the accept operation.

Let’s see an example of Visitor design pattern in Java.

Java




interface ItemElement
{
    public int accept(ShoppingCartVisitor visitor);
}
 
class Book implements ItemElement
{
    private int price;
    private String isbnNumber;
  
    public Book(int cost, String isbn)
    {
        this.price=cost;
        this.isbnNumber=isbn;
    }
  
    public int getPrice()
    {
        return price;
    }
  
    public String getIsbnNumber()
    {
        return isbnNumber;
    }
  
    @Override
    public int accept(ShoppingCartVisitor visitor)
    {
        return visitor.visit(this);
    }
  
}
 
class Fruit implements ItemElement
{
    private int pricePerKg;
    private int weight;
    private String name;
  
    public Fruit(int priceKg, int wt, String nm)
    {
        this.pricePerKg=priceKg;
        this.weight=wt;
        this.name = nm;
    }
  
    public int getPricePerKg()
    {
        return pricePerKg;
    }
  
    public int getWeight()
    {
        return weight;
    }
  
    public String getName()
    {
        return this.name;
    }
  
    @Override
    public int accept(ShoppingCartVisitor visitor)
    {
        return visitor.visit(this);
    }
  
}
 
interface ShoppingCartVisitor
{
  
    int visit(Book book);
    int visit(Fruit fruit);
}
 
class ShoppingCartVisitorImpl implements ShoppingCartVisitor
{
  
    @Override
    public int visit(Book book)
    {
        int cost=0;
        //apply 5$ discount if book price is greater than 50
        if(book.getPrice() > 50)
        {
            cost = book.getPrice()-5;
        }
        else
            cost = book.getPrice();
             
        System.out.println("Book ISBN::"+book.getIsbnNumber() + " cost ="+cost);
        return cost;
    }
  
    @Override
    public int visit(Fruit fruit)
    {
        int cost = fruit.getPricePerKg()*fruit.getWeight();
        System.out.println(fruit.getName() + " cost = "+cost);
        return cost;
    }
  
}
 
class ShoppingCartClient
{
  
    public static void main(String[] args)
    {
        ItemElement[] items = new ItemElement[]{new Book(20, "1234"),
                              new Book(100, "5678"), new Fruit(10, 2, "Banana"),
                              new Fruit(5, 5, "Apple")};
  
        int total = calculatePrice(items);
        System.out.println("Total Cost = "+total);
    }
  
    private static int calculatePrice(ItemElement[] items)
    {
        ShoppingCartVisitor visitor = new ShoppingCartVisitorImpl();
        int sum=0;
        for(ItemElement item : items)
        {
            sum = sum + item.accept(visitor);
        }
        return sum;
    }
  
}


Output

Book ISBN::1234 cost =20
Book ISBN::5678 cost =95
Banana cost = 20
Apple cost = 25
Total Cost = 160






Here, in the implementation if accept() method in all the items are same but it can be different. For example there can be logic to check if item is free then don’t call the visit() method at all.

Advantages :

  • If the logic of operation changes, then we need to make change only in the visitor implementation rather than doing it in all the item classes.
  • Adding a new item to the system is easy, it will require change only in visitor interface and implementation and existing item classes will not be affected.

Disadvantages :

  • We should know the return type of visit() methods at the time of designing otherwise we will have to change the interface and all of its implementations.
  • If there are too many implementations of visitor interface, it makes it hard to extend.

Another example of visitor pattern in C++

CPP




//Write CPP code here
 
#include <iostream>
using namespace std;
 
class Stock
{
  public:
    virtual void accept(class Visitor *) = 0;
     
};
 
class Apple : public Stock
{
  public:
    /*virtual*/ void accept(Visitor *);
    void buy()
    {
        cout << "Apple::buy\n";
    }
    void sell()
    {
        cout << "Apple::sell\n";
    }
     
};
class Google : public Stock
{
  public:
    /*virtual*/ void accept(Visitor *);
    void buy()
    {
        cout << "Google::buy\n";
    }
 
    void sell()
    {
        cout << "Google::sell\n";
    }
};
 
class Visitor
{
  public:
    virtual void visit(Apple *) = 0;
    virtual void visit(Google *) = 0;
    //private:
    static int m_num_apple, m_num_google;
    void total_stocks()
    {
        cout << "m_num_apple " << m_num_apple
             << ", m_num_google " << m_num_google << '\n';
    }
};
int Visitor::m_num_apple = 0;
int Visitor::m_num_google = 0;
class BuyVisitor : public Visitor
{
  public:
    BuyVisitor()
    {
        m_num_apple = m_num_google = 0;
    }
    /*virtual*/ void visit(Apple *r)
    {
        ++m_num_apple;
        r->buy();
        cout << "m_num_apple " << m_num_apple << endl;
    }
    /*virtual*/ void visit(Google *b)
    {
        ++m_num_google;
        b->buy();
        cout << " m_num_google " << m_num_google << '\n';
    }
};
 
class SellVisitor : public Visitor
{
  public:
    /*virtual*/ void visit(Apple *a)
    {
         
        --m_num_apple;
        a->sell();
        cout << "m_num_apple " << m_num_apple << endl;
    }
    /*virtual*/ void visit(Google *g)
    {
        --m_num_google;
        g->sell();
        cout << "m_num_google " << m_num_google << endl;
    }
};
 
void Apple::accept(Visitor *v)
{
    v->visit(this);
}
 
void Google::accept(Visitor *v)
{
    v->visit(this);
}
 
int main()
{
    Stock *set[] = { new Apple, new Google, new Google,
                     new Apple, new Apple, 0 };
 
    BuyVisitor buy_operation;
    SellVisitor sell_operation;
    for (int i = 0; set[i]; i++)
    {
        set[i]->accept(&buy_operation);
    }
    buy_operation.total_stocks();
 
    for (int i = 0; set[i]; i++)
    {
 
        set[i]->accept(&sell_operation);
    }
    sell_operation.total_stocks();
}


Output

Apple::buy
m_num_apple 1
Google::buy
 m_num_google 1
Google::buy
 m_num_google 2
Apple::buy
m_num_apple 2
Apple::buy
m_num_apple 3
m_num_apple 3, m_num_google 2
Apple::sell
m_num_apple 2
Google::sell
m_num_google 1
Google::sell
m_num_google 0
Apple::sell
m_num_apple 1
Apple::sell
m_num_apple 0
m_num_apple 0, m_num_google 0








Previous Article
Next Article

Similar Reads

Visitor Design Pattern in Java
The Visitor Design Pattern is a behavioral design pattern that allows you to separate algorithms or operations from the objects on which they operate. It enables you to add new operations to objects without modifying their structure. Important Topics for Visitor Design Pattern in Java What is the Visitor Design Pattern?Real-Life Example of the Visi
10 min read
Visitor Pattern | JavaScript Design Patterns
The visitor pattern is a behavioral design pattern that allows you to add new behaviors or operations to a set of objects without modifying their structure. It achieves this by separating the algorithm from the objects on which it operates. Important Topics for the Visitor Pattern in JavaScript Design Patterns Characteristics of the Visitor Pattern
12 min read
Visitor Method Design Patterns in C++
A visitor design patterns or visitor method is basically defined as a behavioral design pattern that allows us to define a new operation without changing the classes of the elements on which it operates. It is particularly useful when we have a set of related classes, and we want to perform different operations on each class without modifying their
9 min read
Visitor Method - Python Design Patterns
Visitor Method is a Behavioral Design Pattern which allows us to separate the algorithm from an object structure on which it operates. It helps us to add new features to an existing class hierarchy dynamically without changing it. All the behavioral patterns proved as the best methods to handle the communication between the objects. Similarly, it i
4 min read
Behavioral Design Pattern | JavaScript Design Pattern
Behavioral design patterns are a subset of design patterns in software engineering that deal with the interaction and responsibilities of objects. These patterns focus on how objects communicate and work together to achieve common tasks. Important Topics for the Behavioral Design Pattern in JavaScript Design Patterns Uses Cases of the Behavioral De
8 min read
Difference between Prototype Design Pattern and Flyweight Design Pattern
The major point in Prototype vs. Flyweight Design Pattern is that Prototype Design Pattern is a creational design pattern whereas Flyweight Design Pattern is a structural design pattern. In this post, we will look into this and more differences between the Prototype and Flyweight Design Patterns. Let us begin with a basic understanding of each of t
2 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation details making it less complex to use. Important
4 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Flyweight design pattern:The shared data typically c
4 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise from direct object-to-object communication. Important
5 min read
Difference Between Builder Design Pattern and Factory Design Pattern
Design patterns provide proven solutions to common problems in software design. The Builder and Factory patterns are two popular creational design patterns. The Builder pattern constructs complex objects step by step. In contrast, the Factory pattern creates objects without specifying their exact class. Both patterns streamline object creation but
7 min read
Why is Singleton Design Pattern is Considered an Anti-pattern?
Let us explore why the Singleton pattern, a popular way to ensure only one instance of a class exists, is now seen as problematic in software development. In this article, we will discuss drawbacks such as tight coupling between components, difficulty in unit testing, and issues with scalability in larger applications. Important Topics for Singleto
8 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 min read
Design Patterns Cheat Sheet - When to Use Which Design Pattern?
In system design, selecting the right design pattern is related to choosing the right tool for the job. It's essential for crafting scalable, maintainable, and efficient systems. Yet, among a lot of options, the decision can be difficult. This Design Patterns Cheat Sheet serves as a guide, helping you on the path toward optimal design pattern selec
7 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read
Difference Between Bridge Pattern and Adapter Pattern
The Bridge Pattern and the Adapter Pattern are structural design patterns in object-oriented software development that primarily target the flexibility and reusability of a design. These two patterns have different roles and are used in different scenarios to solve specific design issues. Important Topics for Bridge Pattern vs Adapter Pattern What
5 min read
Difference between Strategy pattern and Command pattern
In software design, patterns provide reusable solutions to common problems. The Strategy and Command patterns are two important behavioral design patterns. The Strategy pattern allows the selection of an algorithm at runtime. The Command pattern encapsulates a request as an object. Understanding the differences between these patterns is crucial for
6 min read
Strangler Pattern in Micro-services | System Design
The Strangler pattern is an architectural approach employed during the migration from a monolithic application to a microservices-based architecture. It derives its name from the way a vine slowly strangles a tree, gradually replacing its growth. Similarly, the Strangler pattern involves replacing parts of a monolithic application with microservice
4 min read
SAGA Design Pattern
SAGA pattern is a design pattern that is a long-lived sequence of smaller transactions. This pattern is used to manage and maintain data consistency across multiple microservices. Each transaction is executed by a single service, and the state changes are broadcasted to other services involved in the Saga. It helps to maintain data consistency by p
7 min read
10 Best Python Design Pattern Books for Beginners to Advanced
Imagine you're building different types of furniture using the same basic materials (like wood, screws, and nails). Instead of starting from scratch every time, you create templates or instructions for making specific types of furniture. These templates tell you what pieces to use, how to assemble them, and how to add unique features. In software p
4 min read
Abstract Factory Pattern | C++ Design Patterns
Abstract Factory Pattern is a creational design pattern used in object-oriented programming. It provides an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern is a way to encapsulate the creation of objects and ensure that they are compatible and properly configured. In this artic
6 min read
Abstract Factory Pattern | JavaScript Design Patterns
Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface to create objects. Important Topics for the Abstr
6 min read
Bridge Method | JavaScript Design Pattern
In software design, as systems grow and evolve, the complexity of their components can increase exponentially. This complexity often arises from the intertwining of different functionalities and features, making the system rigid, less maintainable, and harder to scale. The Bridge design pattern emerges as a solution to this problem, offering a way
9 min read
Proxy Pattern | C++ Design Patterns
Design Patterns are an essential part of software engineering, offering proven solutions to common problems encountered during software development. One such pattern is the Proxy Pattern. The Proxy Pattern is a structural design pattern that provides a surrogate or placeholder for another object, allowing you to control access to it. This pattern c
7 min read
Flyweight Pattern | C++ Design Patterns
A flyweight pattern is a structural design pattern used to optimize memory usage and performance when dealing with a large number of objects that share some common characteristics. It achieves this by separating an object's intrinsic state (shared among multiple objects) from its extrinsic state (unique to each object) and storing the intrinsic sta
9 min read
Introduction to Decorator Pattern in C++ | Design Patterns
The Decorator Pattern is a structural design pattern in software engineering that enables the dynamic addition of new behaviors or responsibilities to individual objects without altering their underlying class structure. It achieves this by creating a set of decorator classes that are used to wrap concrete components, which represent the core funct
12 min read
Memento Method - JavaScript Design Pattern
A behavioral design pattern in JavaScript called Memento focuses on externalizing and capturing an object's internal state so that it can later be restored. When you need to add features like undo/redo functionality, history tracking, or reverting an item to a former state, this pattern is quite helpful. Important Topics for the Memento MethodUnder
6 min read
Prototype Pattern | C++ Design Patterns
When designing software, it's crucial to make it efficient, easy to reuse, and simple to maintain. One way to achieve these goals is by using design patterns, and one such pattern is the Prototype Pattern. In this article, we'll explore the Prototype Design Pattern in the context of C++. Important Topics for the Prototype Pattern in C++ Design Patt
5 min read
Article Tags :