This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Design Patterns
.NET 2.0+

Visitor Design Pattern

The visitor pattern is a design pattern that separates a set of structured data from the functionality that may be performed upon it. This promotes loose coupling and enables additional operations to be added without modifying the data classes.

Testing the Visitor

To test the example we can add some code to the Main method of the console application. The following code creates five employees in a three-level hierarchy. Once the structure is created, a payroll visitor is applied to the organisational structure to output the salary details for each employee. Next, a pay rise visitor increases the monthly salary for each employee by 5%. The payroll visitor is then used again to display the new salaries. Finally, the total increase in salary is displayed.

Manager bob = new Manager();
bob.Name = "Bob";
bob.MonthlySalary = 5000;

Manager sue = new Manager();
sue.Name = "Sue";
sue.MonthlySalary = 4000;

Worker jim = new Worker();
jim.Name = "Jim";
jim.MonthlySalary = 2000;

Worker tom = new Worker();
tom.Name = "Tom";
tom.MonthlySalary = 1800;

Worker mel = new Worker();
mel.Name = "Mel";
mel.MonthlySalary = 1900;


OrganisationalStructure org = new OrganisationalStructure(bob);

PayrollVisitor payroll = new PayrollVisitor();
PayriseVisitor payrise = new PayriseVisitor(0.05);


Console.WriteLine("Total pay increase = {0}.", payrise.TotalIncrease);


Bob paid 5000 + Bonus.
Sue paid 4000 + Bonus.
Tom paid 1800.
Mel paid 1900.
Jim paid 2000.
Bob salary increased by 250.
Sue salary increased by 200.
Tom salary increased by 90.
Mel salary increased by 95.
Jim salary increased by 100.
Bob paid 5250 + Bonus.
Sue paid 4200 + Bonus.
Tom paid 1890.
Mel paid 1995.
Jim paid 2100.
Total pay increase = 735.

21 August 2009