YouTip LogoYouTip

Builder Pattern

# Builder Pattern The Builder pattern is a creational design pattern that lets you construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code. The Builder pattern is a creational design pattern. Its main purpose is to separate the construction process of a complex object from its representation, thereby allowing the creation of objects with different representations. ## Overview ### Intent Separate the construction of a complex object from its representation so that the same construction process can create different representations. ### Problem In software systems, the creation of a complex object is often composed of multiple parts. The combination of these parts often changes, but the algorithm for combining them is relatively stable. ### Solution Use the Builder pattern to separate the parts that vary from those that remain constant. ### Key Code * **Builder**: Creates and provides instances. * **Director**: Manages the dependencies of the built instances and controls the construction process. ### Real-World Examples * Going to KFC, a hamburger, cola, fries, fried chicken wings, etc., are constant, but their combination often changes, generating different "combo meals". * `StringBuilder` in Java. ### Pros * Separates the construction process and representation, making the construction process more flexible and allowing for different representations. * Provides better control over the construction process, hiding the specific construction details. * High code reusability, as the same builder can be reused in different construction processes. ### Cons * If the product has few attributes, the Builder pattern may lead to code redundancy. * Increases the number of classes and objects in the system. ### When to Use * When the internal structure of the object to be generated is complex. * When the internal properties of the object to be generated are interdependent. ### Note The difference from the Factory pattern is that the Builder pattern focuses more on the order of assembling parts. ### Structure The Builder pattern includes the following main roles: * **Product**: The complex object to be built. The product class usually contains multiple parts or attributes. * **Abstract Builder**: Defines an abstract interface for building the product, including methods for building each part of the product. * **Concrete Builder**: Implements the abstract builder interface, specifically determines how to build each part of the product, and is responsible for returning the final built product. * **Director**: Responsible for calling the builder's methods to build the product. The director does not understand the specific construction process, only cares about the order and method of product construction. ## Implementation We assume a business case of a fast-food restaurant, where a typical combo meal can be a Burger and a Cold drink. The Burger can be a Veg Burger or a Chicken Burger, and they are wrapped in a box. The Cold drink can be a Coke or a Pepsi, and they are bottled. We will create an _Item_ interface representing food items (like burgers and cold drinks) and concrete classes implementing the _Item_ interface, as well as a _Packing_ interface representing food packaging and concrete classes implementing the _Packing_ interface. Burgers are wrapped in a box, and cold drinks are bottled. Then we create a _Meal_ class with an _ArrayList_ of _Item_ and a _MealBuilder_ to create different types of _Meal_ objects by combining _Item_. The _BuilderPatternDemo_ class uses _MealBuilder_ to create a _Meal_. ![Image 2: UML diagram of the Builder Pattern](#) ### Step 1 Create an interface representing food items and food packaging. ## Item.java public interface Item{public String name(); public Packing packing(); public float price(); } ## Packing.java public interface Packing{public String pack(); } ### Step 2 Create concrete classes implementing the Packing interface. ## Wrapper.java public class Wrapper implements Packing{ @Override public String pack(){return"Wrapper"; }} ## Bottle.java public class Bottle implements Packing{ @Override public String pack(){return"Bottle"; }} ### Step 3 Create an abstract class implementing the Item interface, providing default functionality. ## Burger.java public abstract class Burger implements Item{ @Override public Packing packing(){return new Wrapper(); } @Override public abstract float price(); } ## ColdDrink.java public abstract class ColdDrink implements Item{ @Override public Packing packing(){return new Bottle(); } @Override public abstract float price(); } ### Step 4 Create concrete classes extending Burger and ColdDrink. ## VegBurger.java public class VegBurger extends Burger{ @Override public float price(){return 25.0 f; } @Override public String name(){return"Veg Burger"; }} ## ChickenBurger.java public class ChickenBurger extends Burger{ @Override public float price(){return 50.5 f; } @Override public String name(){return"Chicken Burger"; }} ## Coke.java public class Coke extends ColdDrink{ @Override public float price(){return 30.0 f; } @Override public String name(){return"Coke"; }} ## Pepsi.java public class Pepsi extends ColdDrink{ @Override public float price(){return 35.0 f; } @Override public String name(){return"Pepsi"; }} ### Step 5 Create a Meal class with the Item objects defined above. ## Meal.java import java.util.ArrayList; import java.util.List; public class Meal{private Listitems = new ArrayList(); public void addItem(Item item){items.add(item); }public float getCost(){float cost = 0.0 f; for(Item item : items){cost += item.price(); }return cost; }public void showItems(){for(Item item : items){System.out.print("Item : "+item.name()); System.out.print(", Packing : "+item.packing().pack()); System.out.println(", Price : "+item.price()); }}} ### Step 6 Create a MealBuilder class, the actual builder class responsible for creating Meal objects. ## MealBuilder.java public class MealBuilder{public Meal prepareVegMeal(){Meal meal = new Meal(); meal.addItem(new VegBurger()); meal.addItem(new Coke()); return meal; }public Meal prepareNonVegMeal(){Meal meal = new Meal(); meal.addItem(new ChickenBurger()); meal.addItem(new Pepsi()); return meal; }} ### Step 7 BuiderPatternDemo uses MealBuilder to demonstrate the Builder Pattern. ## BuilderPatternDemo.java public class BuilderPatternDemo{public static void main(String[]args){MealBuilder mealBuilder = new MealBuilder(); Meal vegMeal = mealBuilder.prepareVegMeal(); System.out.println("Veg Meal"); vegMeal.showItems(); System.out.println("Total Cost: " +vegMeal.getCost()); Meal nonVegMeal = mealBuilder.prepareNonVegMeal(); System.out.println("nn Non-Veg Meal"); nonVegMeal.showItems(); System.out.println("Total Cost: " +nonVegMeal.getCost()); }} ### Step 8 Execute the program, output the result: Veg MealItem : Veg Burger, Packing : Wrapper, Price : 25.0Item : Coke, Packing : Bottle, Price : 30.0Total Cost: 55.0Non-Veg MealItem : Chicken Burger, Packing : Wrapper, Price : 50.5Item : Pepsi, Packing : Bottle, Price : 35.0Total Cost: 85.5 * * * ## Related Articles
← Prototype PatternSingleton Pattern β†’