Visitor Pattern for User Interface and Display

I was browsing the NHibernate forums and came across a post by "thatmikewilliams" who posted the following code:

--------------------------------------------------------

Because this functionality is closely tied to the user interface you should probably use a visitor for this (rather than an overridden method in your class hierarchy).

package test.visitor;
public abstract class Payment {
   interface Visitor {
      Object visit(CardPayment payment);
      Object visit(CashPayment payment);
   }
   public abstract Object accept(Visitor visitor);
}

package test.visitor;
public class CardPayment extends Payment {
   @Override
   public Object accept(Visitor visitor) {
      return visitor.visit(this);
   }
}

package test.visitor;
public class CashPayment extends Payment {
   @Override
   public Object accept(Visitor visitor) {
      return visitor.visit(this);
   }
}

package test.visitor;
public class PaymentDisplayStringVisitor implements Payment.Visitor {
   public Object visit(CardPayment payment) {
      return "CC";
   }
   public Object visit(CashPayment payment) {
      return "CS";
   }
}

package test.visitor;
import java.util.ArrayList;
import java.util.List;
public class Test {

   public static void main(String[] args) {
      List<Payment> payments = new ArrayList<Payment>();
      payments.add(new CashPayment());
      payments.add(new CardPayment());
      
      PaymentDisplayStringVisitor visitor = new PaymentDisplayStringVisitor();
      for (Payment payment : payments) {
         System.out.println(payment.accept(visitor));
      }
   }
}

----------------------------------------------

Using the Visitor Pattern to display domain specific types on a user interface is a nice approach instead of overriding specific methods on your domain object, on top of that, cluttering your domain objects with useless "UI" specific methods like ("get object name").  Pretty interesting approach. :)  Notice the PaymentDisplayStringVisitor returns specific string type based on the type.  Very Cool.  I'll try extending this approach using .NET and Generics and post some code later.

Comments

No comments posted yet.

Leave Your Comment

Title*
Name*
Email (never displayed)
 (will show your gravatar)
Url
Comment*

Please add 4 and 3 and type the answer here:

Preview Your Comment.