Suggested Pages

Thursday, October 18, 2012

Design Pattern Visitor

In this post I will talk about a not common, but useful design pattern called Visitor.

Before describing it, I'm going to show a simple scenario where I will point up common errors in order to emphasize the importance of knowing design pattern over technologies as JPA, EJB etc..

Let us suppose to have a complex domain where we will consider only three classes: Solid, Cone and Cube. These classes belong to a complex domain and their interface should not be modified.

Remember: A class should have only one responsability and the fewest functions as possible.

Now a new task has to be done: You have an heterogeneous structure composed by Solid instances, and you have to create a simple algorithm that prints Solid of this structure in a "Plain Text" format and in a "XML format"..

Common Bad Solution - 1



A common solution to resolve the above task is to add two methods to the Solid interface: printPlainText and printXML. These methods are implemented by Cone and Cube at their manner. Solution is shown above.

HeterogeneousStructure.java

..

public class HeterogeneousStructure {

 private List structures;

 public List getStructures() {
  return structures;
 }

 public void setStructures(List structures) {
  this.structures = structures;
 }
 
}

Solid.java

...

public interface Solid {

 String printPlainText();

 String printXML();
   
}



Cone.java

..

public class Cone implements Solid {

 private int radius;

 private int height;

 public int getRadius() {
  return radius;
 }

 public void setRadius(int radius) {
  this.radius = radius;
 }

 public int getHeight() {
  return height;
 }

 public void setHeight(int height) {
  this.height = height;
 }

 
 public String printPlainText() {
  return "(cone(radius=" + radius + ", height=" + height + "))";
 }

 
 public String printXML() {
  return " " + radius + ", " + height + " ";
 }

}


Cube.java
...

public class Cube implements Solid {

 private int edge;

 public int getEdge() {
  return edge;
 }

 public void setEdge(int edge) {
  this.edge = edge;
 }
 
 public String printPlainText() {
  return "(cube(edge=" + edge + "))";
 }
 
 public String printXML() {
  return "" + edge + "";
 }
}



Suppose a new task says: Create a new algorithm that prints in a JSON format . To accomplish that task you have to add a new method to the Solid interface.
So you have to modified the bean Solid for each new algorithm and this causes the domain is coupled with external features, as the print feature asked for this task.

Common Bad Solution - 2



We have just said that the problem of the first solution is that if you have to add a different print-algorithm, a new method has to be added to the Solid interface.
Another solution that has to be avoided it's that shown below. The basic idea is to create a class that acts like a Strategy and has two methods: the former to visit Cube object and the latter to visit Cone object.

PrintAlgorithmImpl.java

public class PrintAlgorithmImpl implements PrintAlgorithm {

 private PrintStrategy printStrategy;

 public String print(HeterogeneousStructure structure) {
  String printResult = "";
  List structures = structure.getStructures();
  for (Solid solid : structures) {
   
   if (solid instanceof Cube) {
    printResult+=printStrategy.visit((Cube) solid);
   }
      else if (solid instanceof Cone) {
       printResult+=printStrategy.visit((Cone) solid);
   }
  }
  return printResult;
 }

 public PrintStrategy getPrintStrategy() {
  return printStrategy;
 }

 public void setPrintStrategy(PrintStrategy printStrategy) {
  this.printStrategy = printStrategy;
 }
}


PrintStrategy.java

public interface PrintStrategy {

 public String visit(Cone cone);

 public String visit(Cube cube);
}


PrintStrategyXML.java

public class PrintStrategyXML implements PrintStrategy {


 public String visit(Cone cone){
  return "" + cone.getRadius() + "" + cone.getHeight() + "";
 }
 
 public String visit(Cube cube){
  return "" + cube.getEdge() + "";
 }
}


PrintStrategyPlainText.java
public class PrintStrategyPlainText implements PrintStrategy {

 public String visit(Cone cone){
  return "(cone(radius=" + cone.getRadius() + ", height=" + cone.getHeight() + "))";
 }
 
 public String visit(Cube cube){
  return "(cube(edge=" + cube.getEdge() + "))";
 }

}



Solid.java

public interface Solid {

}


Cone.java


public class Cone implements Solid {

 private int radius;

 private int height;

 public int getRadius() {
  return radius;
 }

 public void setRadius(int radius) {
  this.radius = radius;
 }

 public int getHeight() {
  return height;
 }

 public void setHeight(int height) {
  this.height = height;
 }

}


Cube.java

public class Cube implements Solid {

 

 private int edge;

 public int getEdge() {
  return edge;
 }

 public void setEdge(int edge) {
  this.edge = edge;
 }

  
}

The problem of this solution is that you have to discriminate among the subclasses of Solid interface and invoke the right method of PrintStrategy interface.

Visitor Pattern



The Design Pattern Visitor is a behavioural pattern that suggests to reverse the call: the model object is called passing the strategy object used to visit it and not the inverse.

Problem


Consider to use Visitor Design Pattern when:
  • You have to provide many and different operations over a structure with elements having different interfaces;
  • The structure is immutable but operations can change at runtime;
  • You don't want to modify the element of the structure because of new operations on the structure.

Solution


The solution provided by the Design Pattern Visitor is to classify objects into two categories: Visitor and Visited objects. Visited objects permit visitor objects to visit them in a perfect open/closed principle style: Software entities should be open for extension, but closed for modification. Visited objects permit to change the Visitor (alter its behaviour) but their code doesn't change.

Components


  • Visitor:declares a method called visit(ConcreateElement); for each ConcreateElement of the structures;
  • ConcreteVisitor : the concreate class that implements Visitor interface and has the logic of the new operation;
  • Element: defines a method called accept(Visitor v);
  • ConcreateElement: the concreate class that implements Element interface;
  • ObjectStructure: an aggregation of elements that implement Element interface;

PrintAlgorithmImpl.java


public class PrintAlgorithmImpl implements PrintAlgorithm {

 private PrintVisitor printVisitor;

 public PrintVisitor getPrintVisitor() {
  return printVisitor;
 }

 public void setPrintVisitor(PrintVisitor printVisitor) {
  this.printVisitor = printVisitor;
 }

 public String print(HeterogeneousStructure structure) {
  String printResult = "";
  List structures = structure.getStructures();
  for (Solid solid : structures) {
   printResult += solid.accept(printVisitor);
  }
  return printResult;
 }

}

PrintVisitor.java

public interface PrintVisitor {

 public String visit(Cone cone);
 
 public String visit(Cube cube);
}

PrintStrategyPlainText.java


public class PrintVisitorPlainText implements PrintVisitor{

 
 public String visit(Cone cone){
  return "(cone(radius=" + cone.getRadius() + ", height=" + cone.getHeight() + "))";
 }
 
 public String visit(Cube cube){
  return "(cube(edge=" + cube.getEdge() + "))";
 }
}

PrintStrategyPlainText.java


public class PrintVisitorXML implements PrintVisitor{

 
 public String visit(Cone cone){
  return "" + cone.getRadius() + "" + cone.getHeight() + "";
 }
 
 public String visit(Cube cube){
  return "" + cube.getEdge() + "";
 }
}


Solid.java

public interface Solid {

 public String accept(PrintVisitor printVisitor);
}


Cone.java

public class Cone implements Solid {

 private int radius;

 private int height;

 public int getRadius() {
  return radius;
 }

 public void setRadius(int radius) {
  this.radius = radius;
 }

 public int getHeight() {
  return height;
 }

 public void setHeight(int height) {
  this.height = height;
 }

 
 public String accept(PrintVisitor printVisitor) {
  return printVisitor.visit(this);
 }

}


Cube.java

public class Cube implements Solid {

 

 private int edge;

 public int getEdge() {
  return edge;
 }

 public void setEdge(int edge) {
  this.edge = edge;
 }

 public String accept(PrintVisitor printVisitor) {
  return printVisitor.visit(this);
 }
 
}



Conclusions


In conclusion the power of this design pattern lies in the care with which you use. The strength of Visitor is the use of the technique called double dispatch. This technique consists of using a double polymorphism: in fact the execution of the method element.accept (visitor: Visitor) depends on the couple (ConcreateElement, ConcreateVisitor).

See also:


Monday, October 8, 2012

MVC (Model View Controller)

MVC is an architectural pattern that solves the problem of separating the presentation layer from the model layer. It suggests to distinguish three distinct entities:
  • Model
  • View
  • Controller

Model is the layer of model objects. These objects implement the business logic and they usually are the most reusable objects of your web application.
View is the presentation layer of a web application. View layer is responsible for the receiving of user inputs and for the providing of responses to users.
Controller is the layer responsible of managing the user inputs received by the View layer and of performing actions on the Model Objects. It's an intermediate layer that permits the separation between Model and View. Moreover Controller layer , after performing actions on the Model layer, chooses the view to return to users.
The main Java Frameworks that make use of MVC pattern are: Spring and Struts.

Grasp Pattern

GRASP is an acronim for General Responsibility Assignment Software Pattern. These patterns, as the name suggests, deal with assignment of responsibility.
In my opinion, learn these patterns leads to improve the capability of analysis and programming. The main GRASP design patterns are the followings:
  • Controller
  • Creator
  • High Cohesion
  • Indirection
  • Information Expert
  • Low Coupling
  • Protected Variation
  • Pure Fabrication

Controller

Controller suggests to use an object to intercept system calls. This object represents the entire system for a specific use case, therefore it's the first object called when a client calls the system. It delegates to other objects the responsibility to solve a request.

Creator

Creator solves the problem of assigning the responsibility to create objects in a software system. Given two objects A and B, Creator suggests to use A to create B if:
  • A contains or aggregates instance of B
  • A uses B
  • A has the information to inizialize B

High Cohesion

Hign Cohesion suggests to augment the cohesion inside the same class. This means a good class has methods that satisfy the less number of responsibilities as possible. So a good class has a single specific function and all of its methods, have this goal.

Information Expert

Information Expert solves the problem of assigning a specific responsibility to a class. It suggests to give the responsibility to the class that is the best candidate to perform a responsibility. This class has to have the required information to manage this particular responsibility.

Low Coupling

Low Coupling suggests to reduce dependencies among classes. This leads to limit the impact of changes from a class to another.

Indirection

Indirection solves the problem of avoiding coupling among classes. It suggests to introduce an intermediate object that acts as an adapter between two components that have to be decoupled.

Protected Variation

Protected Variation aims to find points of variation/change in a system and suggests to protect these points so that other software components could not suffer from these changes. Java Interfaces are the best candidate to reach his goal. When a client interacts with a software system, it has to know only the direct interlocutor. An interface permits developers to change real implementation of a software component maintaining the same interface exposed.

Pure Fabrication

Pure Fabrication solves the problem of assigning responsibility when either Expert either HighCohesion either Low Coupling are in conflict to assign this responsibility. Pure Fabrication suggests to put the responsibility into a class that is not a class belonging to the application domain. Now this class can follow High Cohesion e Low Coupling design patterns.

Join Types - Tutorial

The most important join types are:
  • Cross Join
  • Inner Join
  • Outer Join
In this page let's consider the following tables:
  1. Player ( id, firstname , surname , salary ,  team) 
  2. Team  ( id , name , city)

Cross Join

The result of a Cross Join is a carthesian products of all table rows. Examples of cross join are the followings:
  • SELECT * FROM Player CROSS JOIN Team (Explicit Cross Join)
  • SELECT * FROM Player,Team (Implicit Cross Join)
As we can see It's not specified any join predicate for matching.

Inner Join

The inner join compares each row of the Employee table with a row from Department table and verifies if the join predicate is satisfied. If it is satisfied the two table rows are combined in one result row. From another point of view the result of an inner join can be seen as the result of a Cartesian product that is filtered through the join predicate.
Examples of inner join are the followings:
  • SELECT * FROM Player player INNER join Team team ON player.team=team.id (Explicit Inner Join)
  • SELECT * FROM Player player, Team team WHERE player.team=team.id (Implicit Inner Join)

Outer Join

An Outer Join produces a row in the result table even if a matching is not found between two rows compared. It acts as a union of the two tables. You have to distinguish from three types of Outer Join: left,right and full. Examples of outer join are the followings:
  • SELECT * FROM Player player LEFT OUTER JOIN Team team ON player.team = team.id
  • SELECT * FROM Player player RIGHT OUTER JOIN Team team ON player.team = team.id
  • SELECT * FROM Player player FULL OUTER JOIN Team team ON player.team = team.id

Grep Recursive


find . -name \* -exec grep "Search" {} \;


Monday, October 1, 2012

Servlet providing JSON Response

In this post we'll see a simple Servlet that provides an HTTP response in JSON format. To print the response in a JSON format, I'm going to use a library called Jackson.

STEP-1: Adding maven dependencies into your pom.xml


pom.xml
<repositories>
    <repository>
 <id>codehaus-snapshots</id>
 <url>http://snapshots.repository.codehaus.org</url>
    </repository>
</repositories>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.10</version>
</dependency>
   


STEP-2: Create the Servlet


JsonServler.java

package com.simonefolinoblogspot.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

public class JsonServlet extends HttpServlet{

 private static final long serialVersionUID = 7905177450045184525L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  System.out.println("JsonServlet--start");
  System.out.println("requestURI="+req.getRequestURI());
  Items items=new Items();
  List listItems = new LinkedList();
  Item item=new Item();
  item.setValue("val1");
  Item item2=new Item();
  item2.setValue("val2");
  listItems.add(item);
  listItems.add(item2);
  items.setItems(listItems);
  resp.setContentType("application/json");
  PrintWriter out = resp.getWriter();
  ObjectMapper mapper = new ObjectMapper(); 
  mapper.writeValue(out, items);
  System.out.println("JsonServlet--end");
 }
 
}


As you can see I made use of ObjectMapper object that permits to print an application domain object in JSON format.
Items.java

package com.simonefolinoblogspot.servlet;

import java.util.List;

public class Items {
 
 private List<Item> items;

 public List<Item> getItems() {
  return items;
 }

 public void setItems(List<Item> items) {
  this.items = items;
 }

 @Override
 public String toString() {
  return "Items [items=" + items + "]";
 }
 
}

Item.java

package com.simonefolinoblogspot.servlet;

public class Item {

 private String value;

 public String getValue() {
  return value;
 }

 public void setValue(String value) {
  this.value = value;
 }

 @Override
 public String toString() {
  return "Item [value=" + value + "]";
 }
}

When the Servlet is invoked the response is in JSON format and is something like this:
Response

{"items":[{"value":"val1"},{"value":"val2"}]}


Suggested Pages