Thursday, November 27, 2014

Bridge Design Pattern - Simple tutorial with an example in Java

Bridge Design Pattern belongs to the Structural Design Patterns category.
As GOF says what you do by using this pattern is "Decouple an abstraction from its implementation so that the two can vary independently."

If I explain it further, in Bridge Design Pattern you decouple a functionality from a class hierarchy and create another interface and a class hierarchy which support that functionality and then create a bridge between these two hierarchies by creating a "has-a" relationship between two interfaces.

You will not understand this at once. But after carefully reading this lesson you will get a good understanding.

As usual Ill take our Vehicle interface to explain this pattern.
Assume that you have an interface called Vehicle which contains createVehicle() method.

public interface Vehicle {
    public void createVehicle();
}

Think that you need to have four types of vehicles. Those are Black Car, White Car, Back Motorbike and White Motorbike. So you will simply create below four classes which implements Vehicle interface.

public class BlackCar implements Vehicle {
@Override
public void createVehicle() {
installCarParts();
paintInBlack();
}

private void paintInBlack() {
  System.out.println("Painting in black...");
}
private void installCarParts() {
  System.out.println("Installing car parts...");
}
}

public class WhiteCar implements Vehicle {
@Override
public void createVehicle() {
  installCarParts();
  paintInBlack();
}

private void paintInBlack() {
  System.out.println("Painting in white...");
}
private void installCarParts() {
  System.out.println("Installing car parts...");
}
}

public class BlackMotorbike implements Vehicle {
@Override
public void createVehicle() {
installCarParts();
  paintInBlack();
}

private void paintInBlack() {
  System.out.println("Painting in black...");
}
private void installCarParts() {
  System.out.println("Installing motorbike parts...");
}
}

public class WhiteMotorbike implements Vehicle {
@Override
public void createVehicle() {
installCarParts();
  paintInBlack();
}

private void paintInBlack() {
  System.out.println("Painting in white...");
}
private void installCarParts() {
  System.out.println("Installing motorbike parts...");
}
}

You see that this is not the best design. For an example your paintInBlack() and paintInWhite() methods are duplicated. This design becomes more complex and less maintainable when the number of implementation classes are higher.
In this kind of situations Bridge Pattern comes to your help.
In Bridge Pattern what you do is create another interface(Painter) which does the painting job and then create another hierarchy of classes which implements this interface. Then you keep a reference to the Painter interface in Vehicle interface.
Now you have two class hierarchies which implement separate two interfaces. Having a reference to Painter interface in Vehicle interface is the bridge between these two hierarchies.
This is the Bridge Design Pattern.
With this pattern, your interfaces and implementation classes will be as below.

public abstract class Vehicle {
  protected Paint painter;
  public abstract void createVehicle();
}

public class Car extends Vehicle {
public Car(Paint painter) {
  this.painter = painter;
}

@Override
public void createVehicle() {
installCarParts();
  painter.paint();
}

private void installCarParts() {
  System.out.println("Installing car parts...");
}
}

public class Motorbike extends Vehicle {
public Motorbike(Paint painter) {
this.painter = painter;
}

@Override
public void createVehicle() {
  installMotorbikeParts();
  painter.paint();
}

private void installMotorbikeParts() {
  System.out.println("Installing motorbike parts...");
}
}

public interface Paint {
  public void paint();
}

public class BlackPaint implements Paint {
@Override
public void paint() {
System.out.println("Painting in black...");
}
}

public class WhitePaint implements Paint {
@Override
public void paint() {
  System.out.println("Painting in white...");
}
}

In your client class now you can create various types of vehicles as below.
public class Test {
    public static void main(String[] args) {
Car whiteCar = new Car(new WhitePaint());
Car blackCar = new Car(new BlackPaint());
Motorbike whiteBike = new Motorbike(new WhitePaint());
Motorbike blackBike = new Motorbike(new WhitePaint());
    }
}

Saturday, November 22, 2014

Abstract Factory - Simple tutorial with an example in Java

    In Factory Method pattern we used a method called factory to create objects.

The concept of Abstract Factory Pattern is having a Factory Class which creates other factories according to the information given. If you remember the Factory Method tutorial you had a Vehicle interface and multiple classes which implement it. You had a factory called VehicleFactory which constructs the correct type of vehicle instance(car bus or van).
This pattern also belongs to the creational patterns group.

The difference in Abstract Factory Pattern is instead of having one VehicleFactory you have multiple factories such as WaterVehicleFactory and LandVehicleFactory ana there is another class which creates the correct factory for you.

See below example.

This is the Vehicle interface.
public interface Vehicle {
}

Below four classes implement above interface.

public class Bus implements Vehicle {
}
public class Car implements Vehicle {
}
public class Ship implements Vehicle {
}
public class Boat implements Vehicle {
}

We can categorize above four classes in to two groups, Land Vehicles and Sea Vehicles. So similarly we can have two factories to create them such as LandVehicleFactory and SeaVehicleFactory.
First we create an super abstract factory class or an interface (AbstractVehicleFactory) and extend LandVehicleFactory and SeaVehicleFactory classes from it as below.


public interface AbstractVehicleFactory {
public Vehicle getVehicle(String size);
}

public class LandVehicleFactory implements AbstractVehicleFactory {
public Vehicle getVehicle(String size) {
if ("large".equals(size)) {
return new Bus();
} else {
return new Car();
}
}
}

public class SeaVehicleFactory implements AbstractVehicleFactory {
public Vehicle getVehicle(String size) {
if("large".equals(size)) {
return new Ship();
} else {
return new Boat();
}
}
}

Finally you need a separate class which is responsible to create and return the correct factory according to the requirement.


public class FactoryCreator {
public static AbstractVehicleFactory getFactory(String terrainType) {
if("sea".equals(terrainType)) {
return new SeaVehicleFactory();
} else if("land".equals(terrainType)) {
return new LandVehicleFactory();
} else {
return null;
}
}
}

I think now you understand this pattern well. You can use below class to test it.


public class Test {
public static void main(String[] args) {
AbstractVehicleFactory factory = FactoryCreator.getFactory("sea");
Vehicle ship = factory.getVehicle("large");
System.out.println(ship.getClass().getSimpleName());
}
}

Thursday, November 20, 2014

Factory Method - Simple tutorial with an example in Java

Factory Method design pattern belongs to the creational design pattern group. Factory method is responsible of creating the correct object according to the information given.

For an example assume that you have an interface called Vehicle and multiple classes which implement it such as Bus, Car and Van. Then when you need to create an instance from one of above classes according to the passenger count, the factory method is responsible to construct and return the correct type of object.

See below example.

This is the Vehicle interface.
public interface Vehicle {
}

Below three classes implement above interface.
public class Bus implements Vehicle {
}

public class Car implements Vehicle {
}

public class Van implements Vehicle {
}

I put my factory method in a separate class so that other classes can use this method easily. This is my class which contains my factory method. When I call the getVehicle() method it returns me the correct type of object according to the passenger count I pass.

public class VehicleFactory {
public static Vehicle getVehicle(int passengerCount) {
if(passengerCount <= 4) {
return new Car();
} else if(passengerCount <= 18) {
return new Van();
} else {
return new Bus();
}
}
}

You can test this method as below.
public class Test {
public static void main(String[] args) {
Vehicle car = VehicleFactory.getVehicle(3);
Vehicle bus = VehicleFactory.getVehicle(25);

System.out.println(car.getClass().getSimpleName());
System.out.println(bus.getClass().getSimpleName());
}
}

Singleton Pattern - Simple tutorial with an example in Java

This pattern belongs to the category of creational design patterns. The concept of this pattern is can be described as below.

"This pattern does not let creating more than one instance of a certain object."

It means you can use this pattern when you want to restrict other classes creating more than one instance of a certain class.
How can we do that.
Think that the name of your class which is needed to be singleton is MySingleton. You can make the class singleton as below.

public class MySingleton {
private static MySingleton mySingleton;

//Make the constructor private so that
//any body cant use this to create instances
private MySingleton() {
}

//Calling this method is the only way of creating an
//instance of this class. If there is no previously created
//instance this method creates an instance and returns
//that. Otherwise returns the previously created instance.
public static MySingleton getInstance() {
if(mySingleton == null) {
mySingleton = new MySingleton();
}
return mySingleton;
}
}

You can test this class as below.

public class Test {
public static void main(String[] args) {
MySingleton ms1 = MySingleton.getInstance();
MySingleton ms2 = MySingleton.getInstance();

System.out.println(ms1 == ms2);//returns true because two instance are the same
}
}

Wednesday, November 19, 2014

Prototype Pattern - Simple tutorial with an example in Java

This pattern belongs to the category of creational design patterns. The core of this pattern can be described simply as below.

"If you want to construct multiple instances of an expensive object, just create one object and clone it multiple times."

✔  Create one instance of expensive object
✔  Clone it when you need another instance of that type
✔  Modify the properties of new(cloned) instance as required.

  Note that this pattern suits only if those instances should have nearly similar properties.
  It is not a must to use Object.clone() method to duplicate the object. You can write your own copy method to do this. To keep this lesson short in my Car class I implements the Cloneable interface and use Object.clone() method in CarCreator class.

Assume that you have a class called Car which can be used to build various types of cars. When using Prototype Pattern what you do is create a car initially and duplicate it when you need more cars.
See this example. This is the Car class.

public class Car implements Cloneable {
int doorCount = 0;

public Car() {
  // complex construction logic here
}

public int getDoorCount() {
return doorCount;
}

public void setDoorCount(int doorCount) {
this.doorCount = doorCount;
}

protected Object clone() {
try {
return super.clone();
} catch (Exception e) {
return null;
}
}

//..more lines here...
}

Ok. Now you should have another class(CarCreator) which is used when you need to create a new Car instance. At the very first time you call this class it goes through the expensive logic and creates an instance of Car object. As well this class keeps that instance for later use. When you request a new car instance at later time it clones the previously saved object and returns.

This is your CarCreator class.

public class CarCreator {
  private Car car;
  
  public Car createCar() {
    if(car == null) {
      car = new Car();//This construction is expensive
      return car;
    } else {
      //since we already have a car in hand we return a clone of that
      return (Car) car.clone();
    }
  }
}

Your client class to check above functionality would be as below.

public class Test implements Cloneable {
  CarCreator carCreator = new CarCreator();
  
  public static void main(String[] args) {
    Test test = new Test();
    //create a luxury car
    Car luxuryCar = test.createVehicle(4);
    //create a sports car
    Car sportsCar = test.createVehicle(2);
    
    System.out.println(luxuryCar.getDoorCount());
    System.out.println(sportsCar.getDoorCount());
  }
  
  private Car createVehicle(int doorCount) {
    Car vehicle = carCreator.createCar();
    vehicle.setDoorCount(doorCount);
    return vehicle;
  }
}

Builder Pattern - Simple tutorial with an example in Java

Builder design pattern belongs to the creational design pattern group. In Builder Pattern you arrange all the steps used to create an object in one separate class(Builder class).
Assume that you have a class or an interfaces called Vehicle. You can create various types of vehicles which are instances of this class(or interface). For an example an instance can be a car or a motorcycle.
Assume that the below class is your Vehicle class which contains complex methods.(Since I need to keep this tutorial short, I am not using an interface here. But note that the best design is making the vehicle class an interface and implementing the Car and Motorcycle classes using that.)

public class Vehicle {
  String name;
  public void addWheels(int count){}
  public void addController(){}
  public void addFuelTank(){}
  public void setName(String name){this.name = name;}
  public String getName(){return this.name;}
}

Building a car or a motorcycle is a complex and multi stepped process. In such cases you can use a VehicleBuilder to make this process organized. In a VehicleBuilder instance there is an instance of Vehicle class and getVehicle() method returns that after constructed.

This is your VehicleBuilder interface.

public interface VehicleBuilder {
  public void setWheels();
  public void setController();
  public void setFuelTank();
  public void setName();
  public Vehicle getVehicle();
}

You can have multiple implementations of this interface. For an example CarBuilder and MotorcycleBuilder.

public class CarBuilder implements VehicleBuilder {
  Vehicle vehicle = new Vehicle();
  public void setWheels() {
    //Fixing 4 wheels (complex logic)
    vehicle.addWheels(4);
  }
  public void setController() {
    //Fix a steering wheel complex logic
    vehicle.addController();
  }
  public void setFuelTank() {
    //Fixing car fuel tank (complex logic)
    vehicle.addFuelTank();
  }
  public void setName() {
    //seting name (complex logic)
    vehicle.setName("car");
  }
  public Vehicle getVehicle() {
    return vehicle;
  }
}

public class MotorcycleBuilder implements VehicleBuilder {
  Vehicle vehicle = new Vehicle();
  public void setWheels() {
    //Fixing 2 wheels (complex logic)
    vehicle.addWheels(2);
  }
  public void setController() {
    //Fixing a handle (complex logic)
    vehicle.addController();
  }
  public void setFuelTank() {
    //Fixing motorcycle fuel tank (complex logic)
    vehicle.addFuelTank();
  }
  public void setName() {
    //setting name (complex logic)
    vehicle.setName("Motorcycle");
  }
  public Vehicle getVehicle() {
    return vehicle;
  }
}

Now in your class you can use this builders to create cars or motorcycles as below.

public class Test {
  public static void main(String[] args) {
//Building a Car
    VehicleBuilder carBuilder = new CarBuilder();
    carBuilder.setName();
    carBuilder.setWheels();
    carBuilder.setController();
    carBuilder.setFuelTank();
    Vehicle car = carBuilder.getVehicle();
    System.out.println(car.getName());
    

//Building a Motorcycle
    VehicleBuilder motorcycleBuilder = new MotorcycleBuilder();
    motorcycleBuilder.setName();
    motorcycleBuilder.setWheels();
    motorcycleBuilder.setController();
    motorcycleBuilder.setFuelTank();
    Vehicle bike = motorcycleBuilder.getVehicle();
    System.out.println(bike.getName());
  }
}

Sunday, November 16, 2014

Simple Jersey client to consume a RESTful web service

In this quick tutorial you will learn to write a Jersey client to consume a RESTful web service.
Below is the web service for which I am going to write a client. You have to start this service first. (You can get a quick knowledge about Jersey RESTful web services by looking at this tutorial)

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class HelloService {
@GET
@Path("/{company}")
@Produces("text/plain")
public Response getWelcomeMessage(@PathParam("company") String company, 
                                   @QueryParam("username") String username) {
String retVal = "Welcome to " + company + " " + username + ".!";
return Response.status(200).entity(retVal).build();
}
}

This is the client which can consume above service.
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class MyClient {
  public static void main(String[] args) {
    try {
      Client client = Client.create();
      WebResource webResource = 
          client.resource("http://localhost:8090/MifeRest/hello");
      ClientResponse response = webResource.path("ABC org") //setting path param
.queryParam("username", "John") //setting query param
.accept("text/plain") //setting accept MIME type
.get(ClientResponse.class); //send GET request
      if (response.getStatus() != 200) {
        System.out.println("Error : " + response.getStatus());
      }

      String responseText = response.getEntity(String.class);
      System.out.println(responseText);  //response body
      System.out.println(response.getHeaders().get("content-type"));  //header value
      } catch (Exception e) {
e.printStackTrace();
      }
  }
}

Saturday, November 8, 2014

Quick and Simple RESTful web service example with Jersey

What is Jersey?
Jersey is a implementation of JAX-RS which is a standard for RESTful Web Services.

Why Jersey is needed when creating RESTful web services?
Jersey is not a must when creating RESTful web services. But Jersey makes our lives easier when creating RESTful services. Below tutorial will show you how.

First create a new web project and name it as RestExample.
Download and add asm-all-x.x.x.jar and jersey-bundle-x.x.x.jar to your project.

Configure the Jersey ServletContainer in your web.xml as below.

<?xml version="1.0" encoding="UTF-8"?>
<web-app .....>
  <servlet>
   <servlet-name>jersy-servlet</servlet-name>
   <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
   <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
   <servlet-name>jersy-servlet</servlet-name>
   <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

Note that all the requests match the above configured url pattern(/*) are sent through the Jersey ServletContainer and if any of them matches with a url pattern of a registered web service(@Path) Jersey point the request to that service.
Now you are ready to create your first RESTful web service with Jersey. Create a new java class and name it as UserManagementService. Now change your class as below and your web service is ready.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@Path("/user")
public class UserManagementService {
@GET
@Path("/profile")
@Produces("application/xml")
public Response getUserProfile() {
String retVal = "<user>" +
                  "<username>John</username>" +
                  "<email>john@example.com</email>" +
                "</user>";
return Response.status(200).entity(retVal).build();
}
}
This simple web service returns a user profile in xml format.
Enter below url in your browser.
http://localhost:8080/RestExample/user/profile

You will get below result.


Note that the annotations are the most important part which convert your plain java class in to a RESTful web service. Those are explained below.

@Path("/user") - If a request url matches this pattern Jersey redirects the request to this class.
@Path("/profile") - If a request redirected to this class matches the pattern "/profile", this method is responsible to serve the request.
@GET - Indicates that this method supports HTTP GET requests. Similarly other valid annotations are " @POST, @PUT, @DELETE and @HEAD". Note only one of these annotations can be applied for one method.
@Produces - This is the response type of this service. This is set as the Content-Type header of the http response. As you know this is used by the browsers to render the output.

Following annotations are also frequently used.

@Consumes - This can be used to specify the media types that can be consumed by the service.
@QueryParam - This is used to extract query string parameters from the request URL.
@PathParam - This is used to get data from request url.

Below is a simple web service which uses @QueryParam,  @PathParam and @HeaderParam annotations.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class HelloService {
 @GET
 @Path("/{firstname}/{lastname}")
 @Produces("text/plain")
 public Response getWelcomeMessage(@QueryParam("company") String company,
                                                        @PathParam("firstname") String firstName, 
                                                        @PathParam("lastname") String lastName
                                   @HeaderParam("Authorization") String token) {
  System.out.println("Auth token is " + token);
 String retVal = "Welcome to " + company + " " + firstName + " " + lastName;
  return Response.status(200).entity(retVal).build();
 }
}

Enter below url in your browser and see the result.
http://localhost:8080/RestExample/hello/John/Daniel?company=ABC

The output will be as below.

Wednesday, November 5, 2014

In Javascript how to iterate over the properties of a JSON object?

When you are working with javascript and JSON you may have faced situations where you need to iterate over the properties of a JSON object.
For an example assume that you receive a JSON response for a http request. Think that you don't know the properties of the object. In such a case you may need to iterate over the properties of the JSON response to get the properties and corresponding values.
There are several ways to do this. But you can do this easily by converting the JSON object in to a javascript.

I will show that below.
Since I need a JSON object for this example I create a JSON objcet by using JSON.stringify() method. The name of my JSON object is jsonObj.

var jsonObj = JSON.stringify({name:'John', age:18});

Ok, now we have a JSON object and lets start.
In order to iterate over the properties you first need to convert the JSON object in to a javascript object as below.

var javascriptObj = JSON.parse(jsonObj);

Now you can iterate and access the properties and values as below.

for (var prop in javascriptObj) {
   alert(prop);//property
   alert(javascriptObj[prop]);//value
}