Thursday, January 27, 2011

Visitor Pattern

Why - As per wikipedia it is "is a way of separating an algorithm from an object structure it operates on".

Lets discuss with an example

- object structure - e.g. getters and setters of a class with attributes interest, principle.
(i.e. getInterest(), getPrinciple()). Lets say the class name having these getters and setters is 'Amount'.

- algorithm to calculate the interest in a class InterestCalculator. While getting the interest from 'Amount', InterestCalculator.calculate needs to be called.

- Amount is Visitable (Visitable is interface which has 'getInterest' method)

class Amount implements Visitable {

getInterest(Visitor visitor) {
visitor.visit(this) ;
}

}

- InterestCalculator is 'Visitor' (Visitor is an interface which have visit method)

class InterestCalculator implements Visitor {

visit(Amount amount) {
// calculation goes here <<<<<<<------------
}
}

- The client (e.g. main method) has to know which visitor (i.e. intetestcalculator) to inject into the accept method.

It invokes it like
Amount a = new Amount() ;
// set values in 'a' object e.g. Principal
a.getInterest(new InterestCalculator)

No comments: