different interfaces. Visitors are also valuable if you
different interfaces. Visitors are also valuable if you have to perform a number of unrelated operations on these classes. On the other hand, as we will see below, Visitors are a good choice only when you do not expect many new classes to be added to your program. Sample Code Let s consider a simple subset of the Employee problem we discussed in the Composite pattern. We have a simple Employee object which maintains a record of the employee s name, salary, vacation taken and number of sick days taken. A simple version of this class is: public class Employee { int sickDays, vacDays; float Salary; String Name; public Employee(String name, float salary, int vacdays, int sickdays) { vacDays = vacdays; sickDays = sickdays; Salary = salary; Name = name; } public String getName() { return Name; } public int getSickdays() { return sickDays; } public int getVacDays() { return vacDays; } public float getSalary() { return Salary; } public void accept(Visitor v) { v.visit(this); } } Note that we have included the accept method in this class. Now let s suppose that we want to prepare a report of the number of vacation days that all employees have taken so far this year. We could just write some code in the client to sum the results of calls to each Employee s getVacDays function, or we could put this function into a Visitor. Since Java is a strongly typed language, your base Visitor class needs to have a suitable abstract visit method for each kind of class in your program. In this first simple example, we only have Employees, so our basic abstract Visitor class is just public abstract class Visitor { public abstract void visit(Employee emp); }
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Cheap Web Hosting services