opencodez

Java Creational Design Patterns – Builder Pattern

Builder pattern is one of the Creational design pattern. This pattern uses step by step approach to build a complex object. So we can say this pattern provides easy way to create a complex object.

NEED OF BUILDER PATTERN

In factory pattern, if client code sending many argument to factory class and if the type of parameters are same, then itxs difficult to maintain the order of the parameters so there may be a possibility of error.

For any class there are set of attributes out of which some are compulsory and some of optional. Factory pattern forces to send all parameters to class because of these restriction optional parameters need to send with value NULL.

So, by using Builder pattern, we can solve the problem with many numbers of optional parameters which is difficult to handle and will be problematic with Factory and Abstract Factory design patterns.

xHere are ALL Java Design Patterns, explained in detail with examplesx

Builder Pattern by Example

Suppose, we have a Customer class with attributes firstName, lastName, age, phone, address and email. So, for this class, we need a constructor where you must pass all information as a parameters to constructor (if you want a immutable class). But in some cases, all attributes are not compulsory, few are optional. Hence, in such cases, we have to write down more constructors which increase the code size.

Builder pattern solves all these problems and provides a way to use many optional parameters with required parameters and preserves the immutability of Customer class.

Letxs see following java Example:

Here we have Customer class for which we are writing CustomerBuilder as a Builder class.

CustomerBuilder class will contain public constructor with mandatory parameters and this builder class will have methods to set optional parameters which returns the builder object after setting the value to the optional parameter.

And last is a build() method which is present in builder class which returns the complex object needed by client program. In customer class private constructor need to be written down by sending Builder class as an argument.

Code

public class Customer {

	private final String firstName; 	// required parameter
	private final String lastName; 		// required parameter
	private final int age; 				// optional parameter
	private final String phone; 		// optional parameter
	private final String address; 		// required parameter
	private final String email; 		// optional parameter

	private Customer(CustomerBuilder builder) {
		this.firstName = builder.firstName;
		this.lastName = builder.lastName;
		this.age = builder.age;
		this.phone = builder.phone;
		this.address = builder.address;
		this.email = builder.email;
	}

	public String getFirstName() {
		return firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public int getAge() {
		return age;
	}

	public String getPhone() {
		return phone;
	}

	public String getAddress() {
		return address;
	}

	public String getEmail() {
		return email;
	}
	
	public String toString() {
		return "Customer: " + this.firstName + ", " + this.lastName + ", " + this.age + ", " + this.phone + ", "
				+ this.address + ", " + this.email;
	}


	public static class CustomerBuilder {

		private String firstName;
		private String lastName;
		private int age;
		private String phone;
		private String address;
		private String email;

		public CustomerBuilder(String firstName, String lastName, String address) {
			this.firstName = firstName;
			this.lastName = lastName;
			this.address = address;
		}

		public CustomerBuilder age(int age) {
			this.age = age;
			return this;
		}

		public CustomerBuilder phone(String phone) {
			this.phone = phone;
			return this;
		}

		public CustomerBuilder email(String email) {
			this.email = email;
			return this;
		}
		
		//Return the final User object
        public Customer build() 
        {
             Customer cust =  new Customer(this);
             return cust;
        }

	}

}

Running the example

public class BuilderDemo {

	public static void main(String[] args) {

		Customer cust1 = new Customer.CustomerBuilder("Leena", "Kadam", "Pune")
						.age(45)
						.phone("9090234567")
						.email("leena@yahoo.com")
						.build();

		System.out.println(cust1);

		Customer cust2 = new Customer.CustomerBuilder("Meena", "Pathak", "Goa") // HERE NOT SENDING email
				.age(32).phone("786795655").build();
		System.out.println(cust2);

		Customer cust3 = new Customer.CustomerBuilder("Sita", "Mane", "Mumbai") // HERE NOT SENDING age, phone, email
				.build();

		System.out.println(cust3);
	}
}

Output

Customer: Leena, Kadam, 45, 9090234567, Pune, leena@yahoo.com
Customer: Meena, Pathak, 32, 786795655, Goa, null
Customer: Sita, Mane, 0, null, Mumbai, null

Conclusion

This all about Builder pattern. As you can see in above program, that there is no need to pass NULL value for optional parameter and we are sending minimum (required parameter) to constructor, these optional parameters are easily handled in Builder design pattern.

xHere are ALL Java Design Patterns, explained in detail with examplesx