Tuesday, February 17, 2015

Creating a custom JSF composite component - Simple Example

In a previous tutorial I showed you how to create a JSF UI component by Extending javax.faces.component.UIComponentBase class. That is not the only way that you can create cutom components in JSF. You can also create your own UI components by combining existing JSF components. This kind of components are called composite components.
This example will show you how to create a composite component by combining h:outputLabel and h:inputText components. Below are the steps taht you need to follow.

1. In WebContent/resources folder create a new folder. This is the folder in which you are going to create your composite component. I name this folder as "custom".
2. Create a new xhtml page in this folder. The code of our composite component will be written in this file. I name this file as labelledInputText.xhtml. Note that then "labelledInputText" will become the name of my composite component.
3. This is the content of my labelledInputText.xhtml file.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:composite="http://java.sun.com/jsf/composite">
<head>
</head>
<body>
  <composite:interface>
    <composite:attribute name="label"/>
    <composite:attribute name="value"/>
  </composite:interface>
  <composite:implementation>
    <h:outputLabel value="#{cc.attrs.label}" /> : 
    <h:inputText value="#{cc.attrs.value}" />
  </composite:implementation>
</body>
</html>

4. The most imporant parts of above code can be explained as below.
xmlns:composite="http://java.sun.com/jsf/composite" - This tag library should be imported at the to of the page.
<composite:interface> - Within these tags the attributes of the composite component are defined.
<composite:attribute> - You can define attributes of the composite component by using this tag.
<composite:implementation> - Within these tags you and add any number of JSF components. You sould design your final composite component between these tags. This is what you see after the final page is rendered.
#{cc.attr....} - You can access the attributes defined in <composite:interface> section like this.
5. Well, now we have created out composite component. We may use it in out xhtml pages as below.

<cust:labelledInputText label="Name" value="#{myBean.message}"/>

See my sample xhtml page(index.xhtml) below where I use this component.

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:tl="http://tech-lead.blogspot.com/tags"
xmlns:cust="http://java.sun.com/jsf/composite/custom">
<h:head>
</h:head>
<body>
  <h:form>
    <cust:labelledInputText label="Name" value="#{myBean.message}"/> 
    <a4j:commandButton value="Ok" action="#{myBean.print()}"/>
  </h:form>
</body>
</html>

Did you note the namespace declaration xmlns:cust="http://java.sun.com/jsf/composite/ custom" at the top of the page. This is needed to use your component in page. The last part(/custom) is the name of the folder you created inside the resources folder(parent fodler of the labelledInputText.xhtml file).

Below is the sample managed bean I use to test this page.

import javax.faces.bean.ManagedBean;

@ManagedBean(name="myBean")
public class MyBean {
  private String message;

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public void print() {
    System.out.println(message);
  }
}

Now run the application and point to the index.xhtml page. Wow! you will see a textbox rendered together with a label on page. Now enter a value in to the text box and press the button. See the console. The value you entered will be printed on it.
Congratulations! It means you have successfully created your first JSF composite component.

Creating a java based custom component in JSF 2.2 - Simple example

In JSF 2.2 it is very easy to create java based custom components. In this tutorial I will show you how to do that.
The component which I am going to create can format the date you enter in to a given pattern.
After creating the component I hope to use it in my xhtml page as below.

<tl:date date="#{myBean.date}" pattern="yyyy-MM-dd">

This component has two attributes. The attribute "date" accepts java.util.Date type value. What my component does is it formats the date using the given pattern(the value entered in to the "pattern" attribute) and displays it on the page.
First I create a java class by extending javax.faces.component.UIComponentBase class. My java class represents the custom date component that I am going to create. This is the code of the class.

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

@FacesComponent(createTag=true, tagName="date", namespace="http://tech-lead.blogspot.com/tags")
public class Date extends UIComponentBase {

  @Override
  public String getFamily() {
    return "custom.component";
  }

  @Override
  public void encodeBegin(FacesContext context) throws IOException {
    java.util.Date date = (java.util.Date) getAttributes().get("date");
    if(date == null) return;
    
    String pattern = (String) getAttributes().get("pattern");
    ResponseWriter writer = context.getResponseWriter();
    
    if(pattern == null || pattern.isEmpty()) {
      writer.write(date.toString());
    } else {
      DateFormat dateFormat = new SimpleDateFormat(pattern);
      writer.write(dateFormat.format(date));
    }
  }
}

Most important points are described below.
@FacesComponent - This annotation is mandatory. This is needed to identify this class as a JSF component.
createTag - Without setting this as 'true' you can't use this component as a tag in xhtml page
tagName - This is the tag name of this component.(The name you use in xhtml page to refer to this component)
namespace - This is the namespace URI you used to import the tag lib which contains this component.
getFamily() - A family name for your components. You can return an arbitrary string here. Returning null may throws runtime exceptions in some JSF implementations.

That is all. The component is created. Now lets use it in our xhtml page.

This is my index.xhtml page.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:tl="http://tech-lead.blogspot.com/tags">

<h:head>
</h:head>
<body>
The date is <tl:date date="#{test.date}" pattern="yyyy-MM-dd" />.
</body>
</html>

This is my managed bean, MyBean.java
import java.util.Date;
import javax.faces.bean.ManagedBean;

@ManagedBean(name="myBean")
public class MyBean {
  private Date date = new Date();

  public Date getDate() {
    return date;
  }

  public void setDate(Date date) {
    this.date = date;
  }
}

Start the application and point to index.jsf page. You will see the formatted date displayed on page.

Monday, February 16, 2015

How to pass javascript parameters to JSF managed bean using RichFaces <a4j:param> component

In your JSF project if you are using RichFaces it is easy to send javascript values from your xhtml page to your managed bean using a4j:param component.
See below example.

My xhtml page is as below.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head>
  <script>
    var jsMessage = 'Hello from javascript!';

    function calculate() {
      return 100 + 50;
    }
  </script>
</h:head>
<body>
  <h:form>
    <a4j:commandButton action="#{test.doIt}" value="Do It">
      <a4j:param value="jsMessage" noEscape="true"
             assignTo="#{test.message}" />
      <a4j:param value="calculate()" noEscape="true"
             assignTo="#{test.valueFromFunction}" />
    </a4j:commandButton>
  </h:form>
</body>
</html>

This is my managed bean.
import javax.faces.bean.ManagedBean;

@ManagedBean(name="test")
public class Test {
  private String message;
  private Double valueFromFunction;

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public Double getValueFromFunction() {
    return valueFromFunction;
  }

  public void setValueFromFunction(Double valueFromFunction) {
    this.valueFromFunction = valueFromFunction;
  }

  public void doIt() {
    System.out.println("Message : " + message);
    System.out.println("Value From Function : " + valueFromFunction);
  }
}

How to use ExecutorService to create and maintain a thread pool in java

The ExecutorService interface and its implementations which are found in java.util.concurrent package are very useful when you need to maintain a thread pool in your application.

What is a thread pool and why it is used? 
Well, first of all think that a thread pool as a collection of threads. Assume that you have a runnable class and assume that you need 'n' number of threads of this class run in parallel. If one thread finished its task and exit you may need to start another thread to make sure that 'n' number of threads are running in parallel.
The ExecutorService can do this and more other stuff for you.
You can add any number of threads in to the ExecutorService. You can tell the ExecutorService how many threads that you want to run in parallel. The ExecutorService is responsible of keeping the given number of threads running in parallel. If one thread went down by finishing its task, the ExecutorService starts another thread to guarantee that given number of threads are running in parallel. ExecutorService does this until all the threads in its pool are executed or until we signal it to stop.
Below example will show you how to create a thread pool using ExecutorService.

As I mentioned earlier you need to have a runnable class which acts as a thread. My runnable class is as below.

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyThread implements Runnable {
  @Override
  public void run() {
    System.out.println(new SimpleDateFormat("hh:mm:ss").format(new Date()));
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      System.out.println("Interrupted.......");
    }
  }
}

This is my code which creates and executes the thread pool.

 java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PoolTest {
  public static void main(String[] args) throws InterruptedException {
    int poolSize = 5;
    ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < 20; i++) {
      MyThread thread = new MyThread();
      threadPool.execute(thread);
    }
    System.out.println("All threads are added to the pool....");
    threadPool.shutdown();
    System.out.println("All Executed....");
  }
}

Run and inspect the output of the above method and you will see that five threads have been executed at the same time.
I'll explain the above code line by line.
ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
This line creates the thread pool. The integer value passed to this method is the number of threads run in parallel.

threadPool.execute(thread);
The execute() method is used to add threads in to the thread pool. As soon as the execute() method is called first time, the ExecutorService starts execution of threads.

threadPool.shutdown();
After adding all the elements in to the thread pool, we calls this method to tell the ExecutorService, that we are not goint to add more threads in to the pool and it may gracefully shuts down after all the threads provided are executed. It should be noted that, this line does not shuts the thread pool down immediately. Instead it permits the thread pool to shuts down after it completely executed all the threads provided. Another thing to keep in mind is that you can't add more threads in to this thread pool after the shutdown() method is called. It will throw a runtime exception.

If you want to tell the ExecutorService to abort all the tasks and shuts down immediately, you can call threadPool.shutdownNow().

If you inspect the output of the above code carefully, you will see that the line "All Executed...." has been printed before the execution of all threads are finished. What is the reason for that. Yes, as you have already understood the thread pool does its job in background and the main thread which contains the line System.out.println("All Executed...."); gets executed in parallel.

What we can do if we need to print this line after all the threads were executed?
The easiest way is to call awaitTermination() after the shutdown() method. This method blocks the main thread until all tasks have completed execution after a shutdown request(or the given timeout occurs, or the current thread is interrupted, whichever happens first).
After adding the awaitTermination() method, the last lines of the above code will be as below.

System.out.println("All threads are added to the pool....");
threadPool.shutdown();
threadPool.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("All Executed....");

Now run the code and you will see that the line "All Executed...." is printed after all the threads are executed.

The other way is to use the ExecutorService.isTerminated() together with Thread.sleep() to check and wait until ExecutorService has been shut down. For an example you can replace the line threadPool.awaitTermination(1, TimeUnit.MINUTES); with below lines.

while (!threadPool.isTerminated()) {
  try {
Thread.sleep(500);
  } catch (InterruptedException e) {
e.printStackTrace();
  }
}

Working with multiple threads is some what tricky and you should act carefully. This tutorial demonstrated the basic usage of ExecutorService to handle thread pools. I think that would help you to design your next multi threaded program in more efficient way.

How to use dynamic parameters in strings in java

In programming it is common to keep commonly used strings in a properties file or as constants and use them in multiple places in your code.

For an example below message can be put in a properties file to be used in different places.
message=The user is not authorized for this operation.

Then you can use this in various places.
But what happens if you need to include the "username" of the user in to this message?
For an example if the username is "john", the message should be

"The user john is not authorized for this operation."

If the username is "tom", the message should be

"The user tom is not authorized for this operation."

In this kind of situations you can use a parametrized messages in your property file as below.
message = The user {0} is not authorized for this operation.

In the places where you use this message you can use java.text.MessageFormat class to replace the parameter with the proper value as below.

String message = properties.getProperty("message");
String formattedMessage = MessageFormat.format(message, "john");

This will print
The user john is not authorized for this operation.

Similarly if you want you can have multiple parameters in the string.
String message = "The user {0} is not authorized for {1} operation.";
String formattedMessage = MessageFormat.format(message, "john", "billing");
System.out.println(formattedMessage);

This will print
The user john is not authorized for billing operation.

Friday, February 13, 2015

How to get/calculate the remaining time for session time out

In Servlet API there is no straight forward method to get the remaining active time of the session. But you can use below two methods provided in HttpSession to calculate this time.

HttpSession.getLastAccessTime() - This method returns the time(in milliseconds) that the client associated with this session sent the last request to the server.
HttpSession.getMaxInactiveInterval() - This is the configured session time out period.

In your servlet you can calculate remaining time as below.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
long now = new Date().getTime();
long lastAccessed = session.getLastAccessedTime();
long timeoutPeriod = session.getMaxInactiveInterval();
long remainingTime = ((timeoutPeriod * 1000) - (now - lastAccessed))/1000;
System.out.println("Remaining time is " + remainingTime + " seconds");
}

Note that if you are using JSF, you can get the associated session as below.
FacesContext ctx = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) ctx.getExternalContext().getSession(false);

Friday, December 19, 2014

Adapter Design Pattern - Simple tutorial with an example in Java

Adapter Design Pattern belongs to the Structural Design Patterns group. You can use this pattern when you need to plug your existing code base to another code base which is not fully compatible with your existing code base. In such cases this pattern guarants the minimal change to your existing code.
Below I am showing you a very simple example which illustrates the use of this pattern. But note that in real world there are more complex situations where this pattern is used.

Assume that you have StudentData class which contains a list of ages of students.
public clas StudentData {
  private List<integer> ages;
}

Now think that for some reason you need to use a third party library which do some complex calculation using ages of students. This is that third party class.
public class ComplexCalculator {
  public int doComplexCalculation(String csv) {
    int result = 0;
    String[] ages = csv.split(",");
    //do complex calculation using ages
    //result = .....
    return result;
  }
}

Look, unfortunately the input type accepted by above method is csv. If you need to use this method you need to convert the list of ages in to a csv string. What do you do now? Change your StudentData class to include the csv generation logic. No. There is a cleaner way. Just create an adapter class(ComplexCalculatorAdapter) and let it do that dirty mediation job for you.
public class ComplexCalculatorAdapter {
  public int callComplexCalculator(List<integer> ages) {

    String csv = null;
    //Logic to create csv string from list
    //String csv = .......
    return new ComplexCalculator().doComplexCalculation(csv);
  }
}
Now in your StudentData class you can call this adapter method as below.
int complexResult = new ComplexCalculatorAdapter().callComplexCalculator(ages);

That is all.
Note that by using Adapter Design Pattern you were able to accomplish the above task with minimal modifications to the existing code.

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;
  }
}