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
Please enter at least three characters to search
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Builder Design Pattern in Java
  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case

Trending

  • The Perfection Trap: Rethinking Parkinson's Law for Modern Engineering Teams
  • ITBench, Part 1: Next-Gen Benchmarking for IT Automation Evaluation
  • Driving DevOps With Smart, Scalable Testing
  • How Kubernetes Cluster Sizing Affects Performance and Cost Efficiency in Cloud Deployments
  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
Likes (14)
Comment
Save
Tweet
Share
91.8K 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
  • Writing DTOs With Java8, Lombok, and Java14+
  • Redefining Java Object Equality
  • Addressing Memory Issues and Optimizing Code for Efficiency: Glide Case

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and 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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!