Visitor pattern

  • Used to decouple operations from object structure – object structure stays in one file, whereas some business methods on this structure are in separate file(s).
  • Used when object structure can’t change but operations performed on it can.
  • Implementation:
      There is a Visitor interface with visit(VisitedElement element) method accepting as an argument a general base type VisitedElement of object hierarchy it wants to visit.
      This hierachy of objects implements VisitedElement interface with void accept(Visitor visitor). The implementation of the accept method is just a simple delegation to the visit method:

    class Book implements VisitedElement {
        ...
        public void accept(Visitor visitor){
            visitor.visit(this);
        }
    }

  • As a result, every concrete visitor has access to the reference of an object in the hierarchy and can apply any operation on its structure.
  • We can have multiple visitor implementations so we can apply multiple operations on visited object data at runtime.
  • Note that you pass this reference of VisitedElement to a vistor’s visit method.
  • A usecase scenario is that when you have a VisitedElement or a group of VisitedElements you can do some business logic on the VisitedElement(s). You can do different business operations by calling accept(Visitor vistor) method with taking different Visitor implementations:

    Visitor shopPromotionVistor=new ShopPromotionVistor();
    Visitor webUrlVistor = new WebUrlVistor();
    for (VistedElement element : elements){
        element.accept(shopPromotionVistor);
        element.accept(webUrlVistor);
    }

  • Advertisements

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s