JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







Visitor Pattern
  • In object-oriented programming and software engineering, the visitor design pattern is a way of
    separating an algorithm from an object structure upon which it operates. A practical result of this separation is the ability to add new operations to existing object cstructures without modifying those structures. Thus, using the visitor pattern helps conformance with
    the open/closed principle.
  • In essence, the visitor allows one to add new virtual functions to a family of classes without modifying the classes themselves; instead, one creates a visitor class
    that implements all of the appropriate specializations of the virtual function. The visitor takes the instance
Purpose

  • Represent an operation to be performed on the elements of an object structure.
  • Visitor lets you define a new operation without changing the classes of the elements on
    which it operates
Application
  • An object structure contains many classes of objects with differing interfaces, and you want to perform perations on these objects that depend on their concrete classes.
  • Many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations. 
  • Visitor lets you keep related operations together by defining them in one class.
  •  When the object structure is shared by many applications, use Visitor to put operations in just those applications that need them.
  • The classes defining the object structure rarely change, but you often want to define new operations over the structure.
  • Changing the object structure classes requires redefining the interface to all visitors,
    which is potentially costly. If the object structure classes change often, then it's probably better to define the operations in those classes.Examples of Memento Pattern

Interaction
  • A client that uses the Visitor pattern must create a ConcreteVisitor object and then
    traverse the object structure, visiting each element with the visitor.
  • When an element is visited, it calls the Visitor operation that corresponds to its class.
  • The element supplies itself as an argument to this operation to let the visitor access its
    state, if necessary.
Examples of Visitor
  • The Visitor pattern represents an operation to be performed on the elements of
    an object structure without changing the classes on which it operates. 
  • This pattern can be observed in the operation of a taxi company.
  •  When a person calls a taxi company (accepting a visitor), the company dispatches a cab to the
    customer. 
  •  Upon entering the taxi the customer, or Visitor, is no longer in control
    of his or her own transportation, the taxi (driver) is.

Example:-

CarElement.java
interface CarElementVisitor {
    void visit(Wheel wheel);
    void visit(Engine engine);
    void visit(Body body);
    void visit(Car car);
    
}
interface CarElement {
    void accept(CarElementVisitor visitor);
// CarElements have to provide accept().

}
class Wheel implements CarElement {
    private String name;
    Wheel(String name) {
        this.name = name;
    }
    String getName() {
        return this.name;
    }
    public void accept(CarElementVisitor visitor) {
        visitor.visit(this);
    }
}
 
class Engine implements CarElement {
    public void accept(CarElementVisitor visitor) {
        visitor.visit(this);
    }
}
 
class Body implements CarElement {
    public void accept(CarElementVisitor visitor) {
        visitor.visit(this);
    }
}
 
class Car implements CarElement{
    CarElement[] elements;
    public CarElement[] getElements() {
        return elements.clone();
// Return a copy of the array of references.
    }
    public Car() {
        this.elements = new CarElement[]
          new Wheel("front left")new Wheel("front right"),
            new Wheel("back left"new Wheel("back right"),
            new Body()new Engine() };
    }
    public void accept(CarElementVisitor visitor) {
  visitor.visit(this);      
    }
 
}
 
class CarElementPrintVisitor implements CarElementVisitor {
    public void visit(Wheel wheel) {      
        System.out.println("Visiting "+ wheel.getName()
                            " wheel");
    }
    public void visit(Engine engine) {
        System.out.println("Visiting engine");
    }
    public void visit(Body body) {
        System.out.println("Visiting body");
    }
 
    public void visit(Car car) {
        System.out.println("\nVisiting car");
        for(CarElement element : car.getElements()) {
            element.accept(this);
        }
        System.out.println("Visited car");
    }
}
 
class CarElementDoVisitor implements CarElementVisitor {
    public void visit(Wheel wheel) {
        System.out.println("Kicking my "+ wheel.getName());
    }
    public void visit(Engine engine) {
        System.out.println("Starting my engine");
    }
    public void visit(Body body) {
        System.out.println("Moving my body");
    }
    public void visit(Car car) {
        System.out.println("\nStarting my car");
        for(CarElement carElement : car.getElements()) {
            carElement.accept(this);
        }
        System.out.println("Started car");
    }
 
}
 

VisitorDemo.java
public class VisitorDemo {
    static public void main(String[] args){
        Car car = new Car();
        car.accept(new CarElementPrintVisitor());
        car.accept(new CarElementDoVisitor());
    }
}

Output:-



Download Zip Code

Example:-


Contact.java
package com.model;

import java.io.Serializable;

public interface Contact extends Serializable {
  public static final String SPACE = " ";

  public String getFirstName();

  public String getLastName();

  public String getTitle();

  public String getOrganization();

  public void setFirstName(String newFirstName);

  public void setLastName(String newLastName);

  public void setTitle(String newTitle);

  public void setOrganization(String newOrganization);
}

ContactImpl.java
package com.model;
public class ContactImpl implements Contact {
  private String firstName;

  private String lastName;

  private String title;

  private String organization;

  public ContactImpl() {
  }

  public ContactImpl(String newFirstName,
 String newLastName,

      String newTitle, String newOrganization) {
    firstName = newFirstName;
    lastName = newLastName;
    title = newTitle;
    organization = newOrganization;
  }

  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public String getTitle() {
    return title;
  }

  public String getOrganization() {
    return organization;
  }

  public void setFirstName(String newFirstName) {
    firstName = newFirstName;
  }

  public void setLastName(String newLastName) {
    lastName = newLastName;
  }

  public void setTitle(String newTitle) {
    title = newTitle;
  }

  public void setOrganization(String newOrganization) {
    organization = newOrganization;
  }

  public String toString() {
    return firstName + SPACE + lastName;
  }
}

DataCreator.java
package com.model;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class DataCreator {
  private static final String DEFAULT_FILE =
 
"data.ser";

  public static void main(String[] args) {
    String fileName;
    if (args.length == 1) {
      fileName = args[0];
    else {
      fileName = DEFAULT_FILE;
    }
    serialize(fileName);
  }

  public static void serialize(String fileName) {
    try {
      serializeToFile(createData(), fileName);
    catch (IOException exc) {
      exc.printStackTrace();
    }
  }

  private static Serializable createData() {
    Contact contact = new ContactImpl("Test""Subject",
 
"Volunteer",
        "United Patterns Consortium");

    Project project = new Project("Project 1",
 
"Test Project");

    Task task1 = new Task("Task 1", contact, 1);
    Task task2 = new Task("Task 2", contact, 1);

    project.addProjectItem(new Deliverable("Deliverable 1",
        "Layer 1 deliverable", contact, 50.050.0));
    project.addProjectItem(task1);
    project.addProjectItem(task2);
    project.addProjectItem(new DependentTask("Dependent Task
1"
, contact,
        11));

    Task task3 = new Task("Task 3", contact, 1);
    Task task4 = new Task("Task 4", contact, 1);
    Task task5 = new Task("Task 5", contact, 1);
    Task task6 = new Task("Task 6", contact, 1);

    DependentTask dtask2 = new DependentTask("Dependent Task
 2"
, contact,
        11);

    task1.addProjectItem(task3);
    task1.addProjectItem(task4);
    task1.addProjectItem(task5);
    task1.addProjectItem(dtask2);

    dtask2.addDependentTask(task5);
    dtask2.addDependentTask(task6);
    dtask2.addProjectItem(new Deliverable("Deliverable 2",
        "Layer 3 deliverable", contact, 50.050.0));

    task3.addProjectItem(new Deliverable("Deliverable 3",
        "Layer 3 deliverable", contact, 50.050.0));
    task4.addProjectItem(new Task("Task 7", contact, 1));
    task4.addProjectItem(new Deliverable("Deliverable 4",
        "Layer 3 deliverable", contact, 50.050.0));
    return project;
  }

  private static void serializeToFile(Serializable content,
 String fileName
)
      throws IOException {
    ObjectOutputStream serOut = new ObjectOutputStream(
        new FileOutputStream(fileName));
    serOut.writeObject(content);
    serOut.close();
  }
}


DataRetriever.java
package com.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DataRetriever {
  public static Object deserializeData(String fileName) {
    Object returnValue = null;
    try {
      File inputFile = new File(fileName);
      if (inputFile.exists() && inputFile.isFile()) {
        ObjectInputStream readIn = new ObjectInputStream(
            new FileInputStream(fileName));
        returnValue = readIn.readObject();
        readIn.close();
      else {
        System.err.println("Unable to locate the
 file " 
+ fileName);
      }
    catch (ClassNotFoundException exc) {
      exc.printStackTrace();

    catch (IOException exc) {
      exc.printStackTrace();

    }
    return returnValue;
  }
}

Deliverable.java
package com.model;

import java.util.ArrayList;

public class Deliverable implements ProjectItem {
  private String name;

  private String description;

  private Contact owner;

  private double materialsCost;

  private double productionCost;

  public Deliverable() {
  }

  public Deliverable(String newName,
String newDescription, Contact newOwner,

      double newMaterialsCost, double newProductionCost) {
    name = newName;
    description = newDescription;
    owner = newOwner;
    materialsCost = newMaterialsCost;
    productionCost = newProductionCost;
  }

  public String getName() {
    return name;
  }

  public String getDescription() {
    return description;
  }

  public Contact getOwner() {
    return owner;
  }

  public double getMaterialsCost() {
    return materialsCost;
  }

  public double getProductionCost() {
    return productionCost;
  }

  public void setMaterialsCost(double newCost) {
    materialsCost = newCost;
  }

  public void setProductionCost(double newCost) {
    productionCost = newCost;
  }

  public void setName(String newName) {
    name = newName;
  }

  public void setDescription(String newDescription) {
    description = newDescription;
  }

  public void setOwner(Contact newOwner) {
    owner = newOwner;
  }

  public void accept(ProjectVisitor v) {
    v.visitDeliverable(this);
  }

  public ArrayList<Object> getProjectItems() {
    return null;
  }
}

DependentTask.java
package com.model;

import java.util.ArrayList;

public class DependentTask extends Task {
  private ArrayList<Object> dependentTasks = new ArrayList();

  private double dependencyWeightingFactor;

  public DependentTask() {
  }

  public DependentTask(String newName, Contact newOwner,
      double newTimeRequired, double newWeightingFactor) {
    super(newName, newOwner, newTimeRequired);
    dependencyWeightingFactor = newWeightingFactor;
  }

  public ArrayList getDependentTasks() {
    return dependentTasks;
  }

  public double getDependencyWeightingFactor() {
    return dependencyWeightingFactor;
  }

  public void setDependencyWeightingFactor(double newFactor) {
    dependencyWeightingFactor = newFactor;
  }

  public void addDependentTask(Task element) {
    if (!dependentTasks.contains(element)) {
      dependentTasks.add(element);
    }
  }

  public void removeDependentTask(Task element) {
    dependentTasks.remove(element);
  }

  public void accept(ProjectVisitor v) {
    v.visitDependentTask(this);
  }
}

Project.java
package com.model;

import java.util.ArrayList;

public class Project implements ProjectItem {
  private String name;

  private String description;

  private ArrayList<Object> projectItems =
 
new ArrayList();

  public Project() {
  }

  public Project(String newName,
String newDescription
) {
    name = newName;
    description = newDescription;
  }

  public String getName() {
    return name;
  }

  public String getDescription() {
    return description;
  }

  public ArrayList getProjectItems() {
    return projectItems;
  }

  public void setName(String newName) {
    name = newName;
  }

  public void setDescription(String newDescription) {
    description = newDescription;
  }

  public void addProjectItem(ProjectItem element) {
    if (!projectItems.contains(element)) {
      projectItems.add(element);
    }
  }

  public void removeProjectItem(ProjectItem element) {
    projectItems.remove(element);
  }

  public void accept(ProjectVisitor v) {
    v.visitProject(this);
  }
}

ProjectCostVisitor.java
package com.model;
public class ProjectCostVisitor
implements ProjectVisitor {
  private double totalCost;

  private double hourlyRate;

  public double getHourlyRate() {
    return hourlyRate;
  }

  public double getTotalCost() {
    return totalCost;
  }

  public void setHourlyRate(double rate) {
    hourlyRate = rate;
  }

  public void resetTotalCost() {
    totalCost = 0.0;
  }

  public void visitDependentTask(DependentTask p) {
    double taskCost = p.getTimeRequired() * hourlyRate;
    taskCost *= p.getDependencyWeightingFactor();
    totalCost += taskCost;
  }

  public void visitDeliverable(Deliverable p) {
    totalCost += p.getMaterialsCost() +
p.getProductionCost
();
  }

  public void visitTask(Task p) {
    totalCost += p.getTimeRequired() * hourlyRate;
  }

  public void visitProject(Project p) {
  }
}


ProjectItem
package com.model;

import java.io.Serializable;
import java.util.ArrayList;

public interface ProjectItem extends Serializable {
  public void accept(ProjectVisitor v);

  public ArrayList getProjectItems();
}

ProjectVisitor.java
package com.model;
public interface ProjectVisitor {
  public void visitDependentTask(DependentTask p);

  public void visitDeliverable(Deliverable p);

  public void visitTask(Task p);

  public void visitProject(Project p);
}

Task.java
package com.model;

import java.util.ArrayList;

public class Task implements ProjectItem {
  private String name;

  private ArrayList<Object> projectItems =
 
new ArrayList();

  private Contact owner;

  private double timeRequired;

  public Task() {
  }

  public Task(String newName, Contact
newOwner, 
double newTimeRequired) {
    name = newName;
    owner = newOwner;
    timeRequired = newTimeRequired;
  }

  public String getName() {
    return name;
  }

  public ArrayList getProjectItems() {
    return projectItems;
  }

  public Contact getOwner() {
    return owner;
  }

  public double getTimeRequired() {
    return timeRequired;
  }

  public void setName(String newName) {
    name = newName;
  }

  public void setOwner(Contact newOwner) {
    owner = newOwner;
  }

  public void setTimeRequired(double
newTimeRequired) {
    timeRequired = newTimeRequired;
  }

  public void addProjectItem(ProjectItem element) {
    if (!projectItems.contains(element)) {
      projectItems.add(element);
    }
  }

  public void removeProjectItem(ProjectItem element) {
    projectItems.remove(element);
  }

  public void accept(ProjectVisitor v) {
    v.visitTask(this);
  }
}

Test.java
package com.test;

import java.io.File;
import java.util.Iterator;

import com.model.DataCreator;
import com.model.DataRetriever;
import com.model.Project;
import com.model.ProjectCostVisitor;
import com.model.ProjectItem;
import com.model.ProjectVisitor;

public class Test {
  public static void main(String[] arguments) {
      System.out.println("Example for the Visitor pattern");
      System.out.println();
      System.out
          .println("This sample will use a
ProjectCostVisitor to calculate"
);
      System.out.println(" the total amount
required to complete a Project."
);
      System.out.println();

      System.out.println("Deserializing a test
 Project for Visitor pattern"
);
      System.out.println();
      if (!(new File("data.ser").exists())) {
        DataCreator.serialize("data.ser");
      }
      Project project = (Project) (DataRetriever.
deserializeData
("data.ser"));

      System.out
          .println("Creating a ProjectCostVisitor,
 to calculate the total cost of the project."
);
      ProjectCostVisitor visitor = new ProjectCostVisitor();
      visitor.setHourlyRate(100);

      System.out
          .println("Moving throuhg the Project,
 calculating total cost"
);
      System.out
          .println(" by passing the Visitor to
each of the ProjectItems."
);
      visitProjectItems(project, visitor);
      System.out.println("The total cost for the project is: "
          + visitor.getTotalCost());
    }

    private static void visitProjectItems(Project
Item item,

        ProjectVisitor visitor) {
      item.accept(visitor);
      if (item.getProjectItems() != null) {
        Iterator subElements = item.getProjectItems().
iterator
();
        while (subElements.hasNext()) {
          visitProjectItems((ProjectItemsubElements.next()
 visitor
);
        }
      }
    }
}

Output:-


Download Zip code

Example:-

Visitor.java
package com.model;

public interface Visitor {
  public int visit(MyInteger wheel);

  public int visit(MyLong engine);
}

AddVisitor.java
package com.model;

public class AddVisitor implements Visitor {
  int value;

  public AddVisitor(int value) {
  this.value = value;
  }

  public int visit(MyInteger i) {
  System.out.println("Adding integer");
  return (value + i.getValue());
  }

  public int visit(MyLong l) {
  System.out.println("Adding long");
  return (value + (intl.getValue());
  }

  }

Visitable.java
package com.model;

public interface Visitable {
  public int accept(Visitor visitor);
}

MyInteger.java
package com.model;

public class MyInteger implements Visitable {
  private int value;

  public MyInteger(int i) {
  this.value = i;
  }

  public int accept(Visitor visitor) {
  return visitor.visit(this);
  }

  public int getValue() {
  return value;
  }
  }

MyLong.java
package com.model;

public class MyLong implements Visitable {
  private long value;

  public MyLong(long l) {
  this.value = l;
  }

  public int accept(Visitor visitor) {
  return visitor.visit(this);
  }

  public long getValue() {
  return value;
  }
  }

SubtractVisitor.java
package com.model;

public class SubtractVisitor implements Visitor {
  int value;

  public SubtractVisitor(int value) {
  this.value = value;
  }

  public int visit(MyInteger i) {
  System.out.println("Subtract integer");
  return (i.getValue() - value);
  }

  public int visit(MyLong l) {
  System.out.println("Subtract long");
  return ((intl.getValue() - value);
  }

  }

VisitorTest.java
package com.test;

import com.model.AddVisitor;
import com.model.MyInteger;
import com.model.MyLong;
import com.model.SubtractVisitor;

public class VisitorTest {

  
  public static void main(String[] args) {
    
    AddVisitor cv = new AddVisitor(10);
    SubtractVisitor sv = new SubtractVisitor(10);
    MyInteger i = new MyInteger(20);
    MyLong l = new MyLong(20);
    System.out.println(i.accept(cv));
    System.out.println(l.accept(cv));

    System.out.println(i.accept(sv));
    System.out.println(l.accept(sv));


  }

}

Output:-


Download Zip Code

Example:-

AbstractTitleInfo.java

package com.model;

public abstract class AbstractTitleInfo {  
     private String titleName;    
     public final void setTitleName(String titleNameIn) {
         this.titleName = titleNameIn;
     }
     public final String getTitleName() {
         return this.titleName;
     }
      
     public abstract void accept(TitleBlurbVisitor
 titleBlurbVisitor
);
  }

BookInfo.java
package com.model;

public class BookInfo extends AbstractTitleInfo {  
     private String author;
      
     public BookInfo(String titleName, String author) {
         this.setTitleName(titleName);
         this.setAuthor(author);
     }    
     
     public void setAuthor(String authorIn) {
         this.author = authorIn;
     }
     public String getAuthor() {
         return this.author;
     }
     
     public void accept(TitleBlurbVisitor titleBlurbVisitor) {
         titleBlurbVisitor.visit(this);
     }
  }

DvdInfo.java
package com.model;

public class DvdInfo extends AbstractTitleInfo {  
     private String star;
     private char encodingRegion;
      
     public DvdInfo(String titleName, 
                    String star, 
                    char encodingRegion) {
         this.setTitleName(titleName);
         this.setStar(star);
         this.setEncodingRegion(encodingRegion);
     }    
     
     public void setStar(String starIn) {
         this.star = starIn;
     }
     public String getStar() {
         return this.star;
     }
     public void setEncodingRegion(char encodingRegionIn) {
         this.encodingRegion = encodingRegionIn;
     }
     public char getEncodingRegion() {
         return this.encodingRegion;
     }
     
     public void accept(TitleBlurbVisitor titleBlurbVisitor) {
         titleBlurbVisitor.visit(this);
     
  }

GameInfo.java
package com.model;

public class GameInfo extends AbstractTitleInfo {  
     public GameInfo(String titleName) {
         this.setTitleName(titleName);
     }    
     
     public void accept(TitleBlurbVisitor titleBlurbVisitor) {
         titleBlurbVisitor.visit(this);
     }
  }

TestTitleVisitor.java
package com.model;

class TestTitleVisitor {
     public static void main(String[] args) {
         AbstractTitleInfo bladeRunner = 
           new DvdInfo("Blade Runner""Harrison Ford",
 
'1');
         AbstractTitleInfo electricSheep = 
           new BookInfo("Do Androids Dream of Electric
Sheep?"

                        "Phillip K. Dick");
         AbstractTitleInfo sheepRaider = 
           new GameInfo("Sheep Raider");
         
         TitleBlurbVisitor titleLongBlurbVisitor = 
           new TitleLongBlurbVisitor();
         
         System.out.println("Long Blurbs:");     
         bladeRunner.accept(titleLongBlurbVisitor);
         System.out.println("Testing bladeRunner   " 
                             titleLongBlurbVisitor.
getTitleBlurb
());
         electricSheep.accept(titleLongBlurbVisitor);
         System.out.println("Testing electricSheep " 
                             titleLongBlurbVisitor.
getTitleBlurb
());
         sheepRaider.accept(titleLongBlurbVisitor);
         System.out.println("Testing sheepRaider   " 
                             titleLongBlurbVisitor.
getTitleBlurb
());
         
         TitleBlurbVisitor titleShortBlurbVisitor = 
           new TitleShortBlurbVisitor();
         
         System.out.println("Short Blurbs:");     
         bladeRunner.accept(titleShortBlurbVisitor);
         System.out.println("Testing bladeRunner   " 
           titleShortBlurbVisitor.getTitleBlurb());
         electricSheep.accept(titleShortBlurbVisitor);
         System.out.println("Testing electricSheep " 
           titleShortBlurbVisitor.getTitleBlurb());
         sheepRaider.accept(titleShortBlurbVisitor);
         System.out.println("Testing sheepRaider   " 
           titleShortBlurbVisitor.getTitleBlurb());
     }
  }      

TitleBlurbVisitor.java
package com.model;

public abstract class TitleBlurbVisitor {
   
     String titleBlurb;
     public void setTitleBlurb(String blurbIn) {
         this.titleBlurb = blurbIn;
     }
     public String getTitleBlurb() {
         return this.titleBlurb;
     }
      
     public abstract void visit(BookInfo bookInfo);
     public abstract void visit(DvdInfo dvdInfo);   
     public abstract void visit(GameInfo gameInfo);

}

TitleLongBlurbVisitor.java
package com.model;

public class TitleLongBlurbVisitor extends TitleBlurbVisitor {
     public void visit(BookInfo bookInfo) {
         this.setTitleBlurb("LB-Book: " 
                             bookInfo.getTitleName() 
                             ", Author: " 
                             bookInfo.getAuthor());
     }   
     
     public void visit(DvdInfo dvdInfo) {
         this.setTitleBlurb("LB-DVD: " 
                             dvdInfo.getTitleName() 
                             ", starring " 
                             dvdInfo.getStar() 
                             ", encoding region: " 
                             dvdInfo.getEncodingRegion());
     }   
     
     public void visit(GameInfo gameInfo) {
         this.setTitleBlurb("LB-Game: " 
                             gameInfo.getTitleName());
     }   
  }

TitleShortBlurbVisitor.java
package com.model;

public class TitleShortBlurbVisitor extends TitleBlurbVisitor {
     public void visit(BookInfo bookInfo) {
         this.setTitleBlurb("SB-Book: " + bookInfo.getTitleName());
     }   
     
     public void visit(DvdInfo dvdInfo) {
         this.setTitleBlurb("SB-DVD: " + dvdInfo.getTitleName());
     }
     
     public void visit(GameInfo gameInfo) {
         this.setTitleBlurb("SB-Game: " + gameInfo.getTitleName());
     }
  }

Output:-


Download Zip code