DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • Builder Design Pattern In Java
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming
  • My ModelMapper Cheat Sheet

Trending

  • OpenID Connect Flows: From Implicit to Authorization Code With PKCE and BFF
  • Documenting a Spring REST API Using Smart-doc
  • How To Use Thread.sleep() in Selenium
  • Application Telemetry: Different Objectives for Developers and Product Managers
  1. DZone
  2. Coding
  3. Languages
  4. Builder Pattern Tutorial with Java Examples

Builder Pattern Tutorial with Java Examples

Learn the Builder Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered

By 
James Sugrue user avatar
James Sugrue
DZone Core CORE ·
Jun. 15, 10 · Tutorial
Like (14)
Save
Tweet
Share
91.3K Views

Join the DZone community and get the full member experience.

Join For Free

Today's pattern is the Builder pattern,which allows for dynamic creation of objects based upon interchangable algorithms. 

Builder in the Real World 

The purpose of the builder pattern is to separate the construction of a complex object from its representation. so that the same construction process can create different representation. An example of this is happy meals at a fast food restaurant. The happy meal typically consists of a hamburger, fries, coke and toy. No matter whether you choose different burgers/drinks, the construction of the kids meal follows the same process. 

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. 

The Builder Pattern

The Builder is a creational pattern - it's used to construct objects such that they can be decoupled from the implementing system. Thedefinition of Builder provided in the original Gang of Four book on DesignPatterns states: 

Allows for object level access control by acting as a pass through entity or a placeholder object.  

Let's take a look at the diagram definition before we go into more detail.



The Builder provides an interface for creating the parts that make up a Product, and ConcreteBuilder provides an implementation of this interface.
The ConcreteBuilder keep track of the representation it creates, provides a way to get the result (Product) as well as constructing the product.
The Director constructs the object through the Builder's interface. The Product is the object, usually complex, that we are constructing. This would include all the classes that define what we are constructing.

The builder pattern will typically use other creational patterns to get products built (e.g. Prototype or Singleton) and will often build a composite.

Would I Use This Pattern?

This pattern is used when object creation algorithms should be decoupled from the system, and multiple representations of creation algorithms are required. This decoupling is useful as you can add new creation functionality to your system without affecting the core code. You also get control over the creation process at runtime with this approach.

An example of the pattern in the Java API would the StringBuilder append method. 

So How Does It Work In Java?

We'll continue with our meals example from earlier.
First, we have the concept of a meal builder, that puts together the parts : main, drink and dessert. The Meal is the composite product that holds all the relevant parts.

// Builder
public abstract class MealBuilder {
  protected Meal meal = new Meal();
  public abstract void buildDrink();
  public abstract void buildMain();
  public abstract void buildDessert();
  public abstract Meal getMeal();
}

Next we create two specific builders, one for kids, one for adults:

public class KidsMealBuilder extends MealBuilder {
  public void buildDrink() {
    // add drinks to the meal
  }
  public void buildMain() {
    // add main part of the meal
  }
  public void buildDessert() {
    // add dessert part to the meal
  }
  public Meal getMeal() {return meal;}
}

public class AdultMealBuilder extends MealBuilder {
  public void buildDrink(){
    // add drinks to the meal
  }
  public void buildMain(){
    // add main part of the meal
  }
  public void buildDessert(){
    // add dessert part to the meal
  }
  public Meal getMeal(){return meal;}
}

In order to kick off the build process, we have a director: 

// Director
public class MealDirector {
  public Meal createMeal(MealBuilder builder) {
    builder.buildDrink();
    builder.buildMain();
    builder.buildDessert();
    return builder.getMeal();
  }
}

And finally we have a client to run all of this:

// Integration with overall application
public class Main {
  public static void main(String[] args) {
    MealDirector director = new MealDirector();
    MealBuilder builder = null;
    if (isKid) {
      builder = new KidsMealBuilder();
    }
    else{
      builder = new AdultMealBuilder();
    }
    Meal meal = director.createMeal(mealBuilder);
  }
}

Watch Out for the Downsides

There's not many downsides that I see to the builder. The decoupling is useful, but the switch statements necessary when using the pattern on it's own aren't very appealing. As with all patterns, it adds complexity when used in the wrong places.

Enjoy the Whole "Design Patterns Uncovered" Series:

Creational Patterns

  • Learn The Abstract Factory Pattern
  • Learn The Builder Pattern
  • Learn The Factory Method Pattern
  • Learn The Prototype Pattern

Structural Patterns

  • Learn The Adapter Pattern
  • Learn The Bridge Pattern
  • Learn The Decorator Pattern
  • Learn The Facade Pattern
  • Learn The Proxy Pattern

Behavioral Patterns

  • Learn The Chain of Responsibility Pattern
  • Learn The Command Pattern
  • Learn The Interpreter Pattern
  • Learn The Iterator Pattern
  • Learn The Mediator Pattern
  • Learn The Memento Pattern
  • Learn The Observer Pattern
  • Learn The State Pattern
  • Learn The Strategy Pattern
  • Learn The Template Method Pattern
  • Learn The Visitor Pattern
Builder pattern Java (programming language) Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Builder Design Pattern In Java
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case
  • Singleton: 6 Ways To Write and Use in Java Programming
  • My ModelMapper Cheat Sheet

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: