Wednesday, 5 January 2011

Understanding Visitor Pattern

Visitor pattern comes under the Behavioral Patterns.


//Visitor Interface
package oops.visitor;
public interface Visitor {
void visit(Section section);
}



//Implementation for Visitor Interface
package oops.visitor;
public class NewEmployee implements Visitor {
public void visit(Section section) {
section.getRequiredInfo();
}
}



//Section Interface representing various deptts of a Company
package oops.visitor;
public interface Section {
void getRequiredInfo();
}



//HR dept
package oops.visitor;
public class HR implements Section {
public void getRequiredInfo() {
System.out.println("Got info from : " + this.getClass().getSimpleName());
}
}



//Accounts dept
package oops.visitor;
public class Accounts implements Section {
public void getRequiredInfo() {
System.out.println("Got info from : " + this.getClass().getSimpleName());
}
}



//Admin dept
package oops.visitor;
public class Admin implements Section {
public void getRequiredInfo() {
System.out.println("Got info from : " + this.getClass().getSimpleName());
}
}



//PD dept
package oops.visitor;
public class PD implements Section {// Product Development Section
public void getRequiredInfo() {
System.out.println("Got info from : " + this.getClass().getSimpleName());
}
}



// Company : A container for various deptts
package oops.visitor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Company {
private List departments = null;
public void accept(Visitor visitor) {
List deptts = getDepartments();
for (Iterator iter = deptts.iterator(); iter.hasNext();) {
Section dept = (Section)iter.next();
visitor.visit(dept);
}
}
public List getDepartments() {
if (null == departments) {
departments = new ArrayList();
departments.add(new Accounts());
departments.add(new Admin());
departments.add(new HR());
departments.add(new PD());
}
return departments;
}
public void setDepartments(List departments) {
this.departments = departments;
}
}



//Main class where NewEmployee visits the Company
package oops.visitor;
public class VisitorPatternEx {
public static void main(String[] args) {
NewEmployee employee = new NewEmployee();
new Company().accept(employee);
}
}

No comments:

Post a Comment