Wednesday, February 20, 2013

design patterns

http://java.dzone.com/articles/design-patterns-visitor

Consider the following code in Walmart system... 

if(item instanceof fruit){...}
else if(item instanceof tool){...}
else if(item instanceof food){...}
else if ...

It sucks, isn't it?

that's one reason why we should use visitor pattern. 

visitor extends IVisitor{
      public long totalPrice;
      public void visit(Fruit f){...}
      public void visit(Food f){...}
      public void visit(Tool t){...}
      ... ...
}

interface Item{
   accept(IVisitor);
}
Item item = new Apple();
apple extends Item{
    accept(IVisitor){
        IVisitor.visit(this);
}
}

item.accept(visitor);






Vistors in the Real World 

A real world analogy always helps with the understanding of a design pattern. One example I have seen for the Visitor pattern in action is a taxi example, where the customer calls orders a taxi, which arrives at his door. Once the person sits in, the visiting taxi is in control of the transport for that person. 
Shopping in the supermarket is another common example, where the shopping cart is your set of elements. When you get to the checkout, the cashier acts as a visitor, taking the disparate set of elements (your shopping), some with prices and others that need to be weighed, in order to provide you with a total. 
It's a difficult pattern to explain in the real world, but things should become clearer as we go through the pattern definition, and take a look at how to use it in code.  
Design Patterns RefcardFor a great overview of the most popular design patterns, DZone'sDesign Patterns Refcard is the best place to start. 

The Visitor Pattern

The Visitor is known as a behavioural pattern, as it's used to manage algorithms, relationships and responsibilities between objects. The definition of Visitor provided in the original Gang of Four book on Design Patterns states: 
Allows for one or more operation to be applied to a set of objects at runtime, decoupling the operations from the object structure. 
What the Visitor pattern actually does is create an external class that uses data in the other classes. If you need to perform operations across a dispate set of objects, Visitor might be the pattern for you. The GoF book says that the Visitor pattern can provide additional functionality to a class without changing it. Let's see how that can work, first by taking a look at the classic diagram definition of  the Visitor pattern:
The core of this pattern is the Visitor interface. This interface defines a visit operation for each type of ConcreteElement in the object structure. Meanwhile, the ConcreteVisitor implements the operations defined in the Visitor interface. The concrete visitor will store local state, typically as it traverses the set of elements. The element interface simply defines an accept method to allow the visitor to run some action over that element - the ConcreteElement will implement this accept method. 

Where Would I Use This Pattern?

The pattern should be used when you have distinct and unrelated operations to perform across a structure of objects. This avoids adding in code throughout your object structure that is better kept seperate, so it encourages cleaner code. You may want to run operations against a set of objects with different interfaces.  Visitors are also valuable if you have to perform a number of unrelated operations across the classes.
In summary, if you want to decouple some logical code from the elements that you're using as input, visitor is probably the best pattern for the job.

So How Does It Work In Java?

The following example shows a simple implementation of the pattern in Java. The example we'll use here is a postage system. Our set of elements will be the items in our shopping cart. Postage will be determined using the type and the weight of each item, and of course depending on where the item is being shipped to. 
Let's create a seperate visitor for each postal region. This way, we can seperate the logic of calculating the total postage cost from the items themselves. This means that our individual elements don't need to know anything about the postal cost policy, and therefore, are nicely decoupled from that logic. 
First, let's create our general visitable  interface: 
1.//Element interface
2.public interface Visitable
3.{
4.public void accept(Visitor visitor);
5.}
Now, we'll create a concrete implementation of our interface, a Book.
01.//concrete element
02.public class Book implements Visitable
03.{
04.private double price;
05.private double weight;
06. 
07.//accept the visitor
08.public void accept(Visitor vistor)
09.{
10.visitor.visit(this);
11.}
12. 
13.public double getPrice()
14.{
15.return price;
16.}
17. 
18.public double getWeight()
19.{
20.return weight;
21.}
22.}
As you can see it's just a simple POJO, with the extra accept method added to allow the visitor access to the element. We could add in other types here to handle other items such as CDs, DVDs or games.


Now we'll move on to the Visitor interface. For each different type of concrete element here, we'll need to add a visit method. As we'll just deal with Book for now, this is as simple as: 
1.public interface Visitor
2.{
3.public void visit(Book book);
4.//visit other concrete items
5.public void visit(CD cd);
6.public void visit(DVD dvd);  
7.}
The implementation of the Vistor can then deal with the specifics of what to do when we visit a book. 
01.public class PostageVisitor implements Visitor
02.{
03.private double totalPostageForCart;    
04.//collect data about the book
05.public void visit(Book book) 
06.{
07.//assume we have a calculation here related to weight and price
08.//free postage for a book over 10     
09.if(book.getPrice() < 10.0)
10.{
11.totalPostageForCart += book.getWeight() * 2;  
12.}
13.}
14. 
15.//add other visitors here
16.public void visit(CD cd){...}
17.public void visit(DVD dvd){...}
18.//return the internal state
19.public double getTotalPostage()
20.{
21.return totalPostageForCart;   
22.}
23.}
As you can see it's a simple formula, but the point is that all the calculation for book postage is done in one central place. 
To drive this visitor, we'll need a way of iterating through our shopping cart, as follows: 
01.public class ShoppingCart
02.{
03.//normal shopping cart stuff
04.private ArrayList<Visitable> items;
05. 
06.public double calculatePostage()
07.{
08.//create a visitor
09.PostageVisitor visitor = new PostageVisitor();
10.//iterate through all items
11.for(Visitable item: items)
12.{
13.item.accept(visitor);
14.}
15.double postage = visitor.getTotalPostage();
16.return postage;
17. 
18.}
19. 
20. 
21.}
Note that if we had other types of item here, once the visitor implements a method to visit that item, we could easily calculate the total postage.
So, while the Visitor may seem a bit strange at first, you can see how much it helps to clean up your code. That's the whole point of this pattern - to allow you seperate out certain logic from the elements themselves, keeping your data classes simple.

Watch Out for the Downsides

The arguments and return types for the visiting methods needs to be known in advance, so the Visitor pattern is not good for situtations where these visited classes are subject to change. Every time a new type of Element is added, every Visitor derived class must be amended. 
Also, it can be difficult to refactor the Visitor pattern into code that wasn't already designed with the pattern in mind. And, when you do add your Visitor code, it can look obscure. The Visitor is powerful, but you should make sure to use it only when necessary.   

No comments:

Post a Comment