Builder Pattern in Java

Builder Pattern is another import design pattern under creational patterns. It is mainly used to solve problems relating to object creation and their functionalities. It so happens that certain objects contain more attributes than they can handle. This gives rise to several internal problems and ultimately leads to codes crashing. To prevent such a mishap, the builder pattern derives complex objects from smaller and simpler objects in a step by step fashion. The final object is independent of the builder objects. By following this design pattern, several different complex objects can be created from a large set of simple objects with varying behaviors.

Definition

The Builder design pattern provides the necessary framework for creating complex objects in a step by step manner. It also facilitates in creating various object representations from the same code while keeping the implementation of the objects abstract to clients.

Example and Code

This code is that of a simple restaurant delivery service. Each item will be broken down into objects and the builder class will take orders to create a meal for each customer.

public interface Menu {                //creating a menu interface in general
public String cusName();
public Del DeliverPackage();
public double cost();

/* We will now create a new class for each food item*/

public abstract class Noodles implements Menu {
@override
public Del DeliveryPackage(){
return new Noodles(); }

@override
public abstract double cost(); }




public abstract class Rice implements Menu {
@override
public Del DeliveryPackage(){
return new Rice(); }

@override
public abstract double cost (); }

.
.
. /* Let us assume a meal class and an order taker class has been created where the Menu objects have been defined and a complete meal for each customer has been taken. Now we will create a builder class to glue all of the different parts together.

public class Testbuilder {
public static void main (String [] args) {
OrderTaker order = new OrderTaker();

Meal veganOrder = order.prepareVeganFood();
System.out.println(“Vegan Meal”);
veganOrder.showMenu();
System.out.println(“Bill: ” + veganOrder.getPrice());

Meal nonvegOrder = order.prepareNonVegFood();
System.out.println(“Non-Veg Meal”);
nonvegOrder.showMenu();
System.out.println(“Bill: ” + nonvegOrder.getPrice());
}
}

When to use the Builder Pattern?

The builder pattern is primarily used by developers where there is a need to produce several complex object representations but writing different codes for each gives rise to logistical and technical problems. If a particular object has been overburdened by attributes, this pattern is also used to decode run-time errors.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.