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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  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

James Sugrue user avatar by
James Sugrue
CORE ·
Jun. 15, 10 · Tutorial
Like (13)
Save
Tweet
Share
89.98K 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
  • Learn The Singleton Pattern

Structural Patterns

  • Learn The Adapter Pattern
  • Learn The Bridge Pattern
  • Learn The Composite Pattern
  • Learn The Decorator Pattern
  • Learn The Facade Pattern
  • Learn The Flyweight 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.

Popular on DZone

  • Building a Scalable Search Architecture
  • Microservices Discovery With Eureka
  • How Do the Docker Client and Docker Servers Work?
  • How To Use Terraform to Provision an AWS EC2 Instance

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: