Here, we will see how to create Visitor Design Pattern with example.
The Visitor design pattern is a behavioral design pattern that allows you to add further operations to objects without modifying them. It lets you define new operations on a set of objects by separating the algorithm from the object structure. In this pattern, you define a visitor class that performs the required operations on elements of a collection.
Example
Consider a company where each employee is an object, and the company occasionally needs to apply different operations on these employees, such as calculating their bonus, reviewing performance, or conducting appraisals. Instead of embedding all these operations within the Employee class, we can use the Visitor pattern.
Here is the image illustrating the Visitor design pattern applied to a company setting. The Developer and Manager are connected to operations like 'Calculating Bonus', 'Performance Review', and 'Appraisal', showing how visitors can perform operations without altering the employee objects.
Consider a company where each employee is an object, and the company occasionally needs to apply different operations on these employees, such as calculating their bonus, reviewing performance, or conducting appraisals. Instead of embedding all these operations within the Employee class, we can use the Visitor pattern.
// Employee hierarchy
public interface IEmployee
{
void Accept(IVisitor visitor);
}
public class Developer : IEmployee
{
public string Name { get; set; }
public void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
}
public class Manager : IEmployee
{
public string Name { get; set; }
public void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
}
// Visitor interface
public interface IVisitor
{
void Visit(Developer developer);
void Visit(Manager manager);
}
// Concrete visitor
public class BonusVisitor : IVisitor
{
public void Visit(Developer developer)
{
Console.WriteLine($"Bonus given to Developer {developer.Name}");
}
public void Visit(Manager manager)
{
Console.WriteLine($"Bonus given to Manager {manager.Name}");
}
}
// Usage
class Program
{
static void Main(string[] args)
{
List<IEmployee> employees = new List<IEmployee>
{
new Developer { Name = "Rohatash" },
new Manager { Name = "Mohit" }
};
IVisitor bonusVisitor = new BonusVisitor();
foreach (var employee in employees)
{
employee.Accept(bonusVisitor);
}
}
}
Output
Compiler Design - In a compiler, the abstract syntax tree (AST) is a complex structure with many different node types (for expressions, statements, etc.). Different operations, such as interpreting, compiling, or type-checking, can be performed on these nodes using the Visitor pattern.
Document Processing - In a document processing system, you can have different elements like paragraphs, tables, and images. The Visitor pattern allows performing various operations like rendering, exporting to different formats, or spell-checking without altering the document structure.