Sunday, August 29, 2010

Visitor pattern

Visitor Pattern :
-----------------------

When to Use the Visitor Pattern

You should consider using a Visitor pattern when you want to perform an operation on the data contained in a number of objects that have different interfaces. Visitors are also valuable if you must perform a number of unrelated operations on these classes. Visitors are a useful way to add function to class libraries or frameworks for which you either do not have the source or cannot change thesource for other technical (or political) reasons. In these latter cases, you simply subclass the classes of the framework and add the accept method to each subclass.


Let's consider a simple subset of the Employee problem discussed in the Composite pattern. We have a simple Employee object that maintains a record of the employee's name, salary, number of vacation days taken, and number of sick days taken. A simple version of this class is the following:

Since Java is a strongly typed language, our base Visitor class needs to have a suitable abstract visit method for each kind of class in the program. In the following first example of our basic abstract visitor class, we have only Employees.

public abstract class Visitor {     
public abstract void visit(Employee emp);     
public abstract void visit(Boss emp); 
} 

Notice that there is no indication what the Visitor does with each class in either the client classes or the abstract Visitor class. We can in fact write a whole lot of Visitors that do different things to the classes in our program. The first Visitor that we write sums the vacation data for all employees.

public class VacationVisitor extends Visitor {     
protected int total_days;     
public VacationVisitor() {         total_days = 0;     }     //--------------     
public void visit(Employee emp) {         total_days += emp.getVacDays();      }    //--------------     
public void visit(Boss boss) {         total_days += boss.getVacDays();     }     //--------------     
public int getTotalDays() {         return total_days;     } }




No comments:

Post a Comment