Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Java Design Patterns Tutorial
Next article icon

Visitor Method – Python Design Patterns

Last Updated : 21 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 is used when we have to perform an operation on a group of similar kinds of objects.
A Visitor Method consists of two parts: 

  • method named as Visit() implemented by the visitor and used and called for every element of the data structure.
  • Visitable classes providing Accept() methods that accept a visitor

Design Components

  • Client: The Client class acts as the consumer of the classes of the visitor design pattern. It can access the data structure objects and can instruct them to accept a visitor for the future processing.
  • Visitor: An Abstract class which is used to declare visit operations for all visitable classes.
  • Concrete Visitor: Each Visitor will be responsible for different operations. For each type of visitor all the visit methods, declared in abstract visitor, must be implemented.
  • Visitable: Accept operations is declared by this class. It also act as the entry point which enables an object to be visited by visitor.
  • Concrete Visitable: These classes implement the Visitable class and defines the accept operation. The visitor object is passed to this object using the accept operation.

Problem without using Visitor Method

Imagine you are handling the Software management of GeeksforGeeks and they have started certain courses such as DSA, SDE, and STL which are definitely useful for students who are preparing for the product based companies. But how will you handle all the data of Courses, Instructors, students, classes, IDs in your database? If you go with a simple direct approach to handle such a situation, you will definitely end up with a mess only. 

Visitor-problem-diagram

Visitor-problem-diagram

Solution using Visitor Method

Let’s look at the solution to the above-described problem. The Visitor method suggests adding a new behavior in a separate class called Visitor class instead of mixing it with the already existing classes. We will pass the original object to the visitor’s method as parameters such that the method will access all the necessary information. 

Python
""" The Courses hierarchy cannot be changed to add new     functionality dynamically. Abstract Crop class for  Concrete Courses_At_GFG classes: methods defined in this class  will be inherited by all Concrete Courses_At_GFG classes."""  class Courses_At_GFG:      def accept(self, visitor):         visitor.visit(self)      def teaching(self, visitor):         print(self, "Taught by ", visitor)      def studying(self, visitor):         print(self, "studied by ", visitor)       def __str__(self):         return self.__class__.__name__   """Concrete Courses_At_GFG class: Classes being visited.""" class SDE(Courses_At_GFG): pass  class STL(Courses_At_GFG): pass  class DSA(Courses_At_GFG): pass   """ Abstract Visitor class for Concrete Visitor classes:  method defined in this class will be inherited by all  Concrete Visitor classes.""" class Visitor:      def __str__(self):         return self.__class__.__name__   """ Concrete Visitors: Classes visiting Concrete Course objects.  These classes have a visit() method which is called by the  accept() method of the Concrete Course_At_GFG classes.""" class Instructor(Visitor):     def visit(self, crop):         crop.teaching(self)   class Student(Visitor):     def visit(self, crop):         crop.studying(self)   """creating objects for concrete classes""" sde = SDE() stl = STL() dsa = DSA()  """Creating Visitors""" instructor = Instructor() student = Student()  """Visitors visiting courses""" sde.accept(instructor) sde.accept(student)  stl.accept(instructor) stl.accept(student)  dsa.accept(instructor) dsa.accept(student) 

Output

SDE Taught by  Instructor
SDE studied by Student
STL Taught by Instructor
STL studied by Student
DSA Taught by Instructor
DSA studied by Student

UML Diagram

Following is the UML diagram for Visitor Method

UML-diagram-visitor-method

Advantages

  • Open/Closed principle: Introducing new behavior in class is easy which can work with objects of different classes without making changes in these classes.
  • Single Responsibility Principle: Multiple versions of same behavior can be operated into the same class.
  • Addition of entities: Adding an entity in Visitor Method is easy as we have to make changes in visitor class only and it will not affect the existing item.
  • Updating Logic: If the logic of operation is updated, then we need to make change only in the visitor implementation rather than doing it in all the item classes.

Disadvantages

  • Lots of Updates: We have to update each and every visitor whenever a class get added or removed from the primary hierarchy
  • Hard to Extend: If there are too many visitor classes then it becomes really hard to extend the whole interface of the class.
  • Lack of Access: Sometimes visitors might not have the access to private field of certain classes that they are supposed to work with.

Applicability

  • Recursive structures: Visitor Method works really well with recursive structures like directory trees or XML structures. The Visitor object can visit each node in the recursive structure
  • Performing Operations: We can use the visitor method when we have to perform operations on all the elements of the complex object like Tree.

Further Read – Visitor Method in C++



Next Article
Java Design Patterns Tutorial
author
chaudhary_19
Improve
Article Tags :
  • Design Pattern
  • Python
  • System Design
  • python-design-pattern
Practice Tags :
  • python

Similar Reads

  • Python Design Patterns Tutorial
    Design patterns in Python are communicating objects and classes that are customized to solve a general design problem in a particular context. Software design patterns are general, reusable solutions to common problems that arise during the design and development of software. They represent best pra
    8 min read
  • Creational Software Design Patterns in Python

    • Factory Method - Python Design Patterns
      Factory Method is a Creational Design Pattern that allows an interface or a class to create an object, but lets subclasses decide which class or object to instantiate. Using the Factory method, we have the best ways to create an object. Here, objects are created without exposing the logic to the cli
      4 min read
    • Abstract Factory Method - Python Design Patterns
      Abstract Factory Method is a Creational Design pattern that allows you to produce the families of related objects without specifying their concrete classes. Using the abstract factory method, we have the easiest ways to produce a similar type of many objects. It provides a way to encapsulate a group
      4 min read
    • Builder Method - Python Design Patterns
      Builder Method is a Creation Design Pattern which aims to "Separate the construction of a complex object from its representation so that the same construction process can create different representations." It allows you to construct complex objects step by step. Here using the same construction code
      5 min read
    • Prototype Method Design Pattern in Python
      The Prototype Method Design Pattern in Python enables the creation of new objects by cloning existing ones, promoting efficient object creation and reducing overhead. This pattern is particularly useful when the cost of creating a new object is high and when an object's initial state or configuratio
      6 min read
    • Singleton Method - Python Design Patterns
      Prerequisite: Singleton Design pattern | Introduction What is Singleton Method in PythonSingleton Method is a type of Creational Design pattern and is one of the simplest design patterns available to us. It is a way to provide one and only one object of a particular type. It involves only one class
      5 min read
    • Structural Software Design Patterns in Python

      • Adapter Method - Python Design Patterns
        Adapter method is a Structural Design Pattern which helps us in making the incompatible objects adaptable to each other. The Adapter method is one of the easiest methods to understand because we have a lot of real-life examples that show the analogy with it. The main purpose of this method is to cre
        4 min read
      • Bridge Method - Python Design Patterns
        The bridge method is a Structural Design Pattern that allows us to separate the Implementation Specific Abstractions and Implementation Independent Abstractions from each other and can be developed considering as single entities.The bridge Method is always considered as one of the best methods to or
        5 min read
      geeksforgeeks-footer-logo
      Corporate & Communications Address:
      A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
      Registered Address:
      K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
      GFG App on Play Store GFG App on App Store
      Advertise with us
      • Company
      • About Us
      • Legal
      • Privacy Policy
      • In Media
      • Contact Us
      • Advertise with us
      • GFG Corporate Solution
      • Placement Training Program
      • Languages
      • Python
      • Java
      • C++
      • PHP
      • GoLang
      • SQL
      • R Language
      • Android Tutorial
      • Tutorials Archive
      • DSA
      • Data Structures
      • Algorithms
      • DSA for Beginners
      • Basic DSA Problems
      • DSA Roadmap
      • Top 100 DSA Interview Problems
      • DSA Roadmap by Sandeep Jain
      • All Cheat Sheets
      • Data Science & ML
      • Data Science With Python
      • Data Science For Beginner
      • Machine Learning
      • ML Maths
      • Data Visualisation
      • Pandas
      • NumPy
      • NLP
      • Deep Learning
      • Web Technologies
      • HTML
      • CSS
      • JavaScript
      • TypeScript
      • ReactJS
      • NextJS
      • Bootstrap
      • Web Design
      • Python Tutorial
      • Python Programming Examples
      • Python Projects
      • Python Tkinter
      • Python Web Scraping
      • OpenCV Tutorial
      • Python Interview Question
      • Django
      • Computer Science
      • Operating Systems
      • Computer Network
      • Database Management System
      • Software Engineering
      • Digital Logic Design
      • Engineering Maths
      • Software Development
      • Software Testing
      • DevOps
      • Git
      • Linux
      • AWS
      • Docker
      • Kubernetes
      • Azure
      • GCP
      • DevOps Roadmap
      • System Design
      • High Level Design
      • Low Level Design
      • UML Diagrams
      • Interview Guide
      • Design Patterns
      • OOAD
      • System Design Bootcamp
      • Interview Questions
      • Inteview Preparation
      • Competitive Programming
      • Top DS or Algo for CP
      • Company-Wise Recruitment Process
      • Company-Wise Preparation
      • Aptitude Preparation
      • Puzzles
      • School Subjects
      • Mathematics
      • Physics
      • Chemistry
      • Biology
      • Social Science
      • English Grammar
      • Commerce
      • World GK
      • GeeksforGeeks Videos
      • DSA
      • Python
      • Java
      • C++
      • Web Development
      • Data Science
      • CS Subjects
      @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
      We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
      Lightbox
      Improvement
      Suggest Changes
      Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
      geeksforgeeks-suggest-icon
      Create Improvement
      Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
      geeksforgeeks-improvement-icon
      Suggest Changes
      min 4 words, max Words Limit:1000

      Thank You!

      Your suggestions are valuable to us.

      What kind of Experience do you want to share?

      Interview Experiences
      Admission Experiences
      Career Journeys
      Work Experiences
      Campus Experiences
      Competitive Exam Experiences