Java Design Patterns Visitor Patterns

Introduction

Visitor Patterns perform an operation on the elements of an object structure.

Use case

  • Use file visitor to visit all files in folder tree.

Example

interface Visitor {
   void visit(MyClass myClassElement);
}

interface Visitable {
   void accept(Visitor visitor);
}

class MyClass implements Visitable {
   private int myInt = 5;

   public int getMyInt() {
      return myInt;
   }/*  w  ww . jav  a  2 s .  c  o m*/

   public void setMyInt(int myInt) {
      this.myInt = myInt;
   }

   @Override
   public void accept(Visitor visitor) {
      System.out.println("Initial value of the integer :" + myInt);
      visitor.visit(this);
      System.out.println("Value of the integer now :" + myInt);
   }
}

class MyVisitor implements Visitor {
   @Override
   public void visit(MyClass myClassElement) {
      System.out.println("Visitor is trying to change the integer value");
      myClassElement.setMyInt(100);
      System.out.println("Exiting from Visitor visit");
   }
}

public class Main {
   public static void main(String[] args) {
      Visitor v = new MyVisitor();
      MyClass myClass = new MyClass();
      myClass.accept(v);
   }
}



PreviousNext

Related