There are many cases where, you do not need to provide values for all the variables and it is still a valid object, for example Java HttpClient. To this class you just have to provide a very basic minimum values and it will work.
In the classes, where an instance isĀ expected to work with default values or with no values.
In such, cases we use builder pattern to create an object.
We have an inner class which does the job of setting values to the member variables of outer class.
The below code is a static inner class, which does the job of creating an instance and returning it to the user.
static class ItineraryBuilder { private Date checkInDate; public ItineraryBuilder checkIn(final Date checkInDate){ this.checkInDate = checkInDate; return this; } private Date checkOutDate; public ItineraryBuilder checkOut(final Date checkOutDate){ this.checkOutDate = checkOutDate; return this; } private int noOfGuests ; public ItineraryBuilder noOfGuests(final int noOfGuests){ this.noOfGuests = noOfGuests; return this; } private int noOfBeds; public ItineraryBuilder noOfBeds(final int noOfBeds){ this.noOfBeds = noOfBeds; return this; } private String destination; public ItineraryBuilder destination(final String destination){ this.destination = destination; return this; } public Itinerary travelPlan(){ if(null == destination || destination.trim().isEmpty()) throw new IllegalArgumentException("Please provide destination."); final Itinerary travelPlan = new Itinerary (); travelPlan.checkInDate = this.checkInDate; travelPlan.checkOutDate = this.checkOutDate; travelPlan.noOfGuests = this.noOfGuests; travelPlan.noOfBeds = this.noOfBeds; travelPlan.destination = this.destination; return travelPlan; } }
This is the outer class, without inner static class, which I have provided above.
public class Itinerary { private Date checkInDate; private Date checkOutDate; private int noOfGuests; private int noOfBeds; private String destination; public Date checkInDate(){ return this.checkInDate; } public Date checkOutDate(){ return this.checkOutDate(); } public int noOfGuests(){ return this.noOfGuests; } public int noOfBeds(){ return this.noOfBeds; } public String destination(){ return this.destination; }
I have written a test class to run this builder class.
public class ItineraryTest{ public static void main(String[] args){ final Itinerary travelPlan = (new Itinerary.ItineraryBuilder()) .checkIn(new Date()) .checkOut(new Date()) .destination("Maldives") .noOfGuests(1) .noOfBeds(1) .travelPlan(); System.out.println("Current Travel Plan"); System.out.println(travelPlan); } }
You can see the entire code over here.