Files
java-design-patterns/step-builder
Ilkka Seppälä 6cd2d0353a docs: Content SEO updates (#2990)
* update yaml frontmatter format

* update abstract document

* update abstract factory

* use the new pattern template

* acyclic visitor seo

* adapter seo

* ambassador seo

* acl seo

* aaa seo

* async method invocation seo

* balking seo

* bridge seo

* builder seo

* business delegate and bytecode seo

* caching seo

* callback seo

* chain seo

* update headings

* circuit breaker seo

* client session + collecting parameter seo

* collection pipeline seo

* combinator SEO

* command seo

* cqrs seo

* commander seo

* component seo

* composite seo

* composite entity seo

* composite view seo

* context object seo

* converter seo

* crtp seo

* currying seo

* dao seo

* data bus seo

* data locality seo

* data mapper seo

* dto seo

* decorator seo

* delegation seo

* di seo

* dirty flag seo

* domain model seo

* double buffer seo

* double checked locking seo

* double dispatch seo

* dynamic proxy seo

* event aggregator seo

* event-based asynchronous seo

* eda seo

* event queue seo

* event sourcing seo

* execute around seo

* extension objects seo

* facade seo

* factory seo

* factory kit seo

* factory method seo

* fanout/fanin seo

* feature toggle seo

* filterer seo

* fluent interface seo

* flux seo

* flyweight seo

* front controller seo

* function composition seo

* game loop seo

* gateway seo

* guarded suspension seo

* half-sync/half-async seo

* health check seo

* hexagonal seo

* identity map seo

* intercepting filter seo

* interpreter seo

* iterator seo

* layers seo

* lazy loading seo

* leader election seo

* leader/followers seo

* lockable object seo

* rename and add seo for marker interface

* master-worker seo

* mediator seo

* memento seo

* metadata mapping seo

* microservice aggregator seo

* api gw seo

* microservices log aggregration seo

* mvc seo

* mvi seo

* mvp seo

* mvvm seo

* monad seo

* monitor seo

* monostate seo

* multiton seo

* mute idiom seo

* naked objects & notification seo

* null object seo

* object mother seo

* object pool seo

* observer seo

* optimistic locking seo

* page controller seo

* page object seo

* parameter object seo

* partial response seo

* pipeline seo

* poison pill seo

* presentation model seo

* private class data seo

* producer-consumer seo

* promise seo

* property seo

* prototype seo

* proxy seo

* queue-based load leveling seo

* reactor seo

* registry seo

* repository seo

* RAII seo

* retry seo

* role object seo

* saga seo

* separated interface seo

* serialized entity seo

* serialized lob seo

* servant seo

* server session seo

* service layer seo

* service locator seo

* service to worker seo

* sharding seo

* single table inheritance seo

* singleton seo

* spatial partition seo

* special case seo

* specification seo

* state seo

* step builder seo

* strangler seo

* strategy seo

* subclass sandbox seo

* table module seo

* template method seo

* throttling seo

* tolerant reader seo

* trampoline seo

* transaction script seo

* twin seo

* type object seo

* unit of work seo

* update method seo

* value object seo

* version number seo

* virtual proxy seo

* visitor seo

* seo enhancements

* seo improvements

* SEO enhancements

* SEO improvements

* SEO additions

* SEO improvements

* more SEO improvements

* rename hexagonal + SEO improvements

* SEO improvements

* more SEO stuff

* SEO improvements

* SEO optimizations

* SEO enhancements

* enchance SEO

* improve SEO

* SEO improvements

* update headers
2024-06-08 19:54:44 +03:00
..
2019-12-07 18:03:49 +02:00
2024-05-23 18:40:52 +03:00
2022-09-14 23:22:24 +05:30
2024-06-08 19:54:44 +03:00

title, shortTitle, description, category, language, tag
title shortTitle description category language tag
Step Builder Pattern in Java: Crafting Fluent Interfaces for Complex Object Construction Step Builder Master the Step Builder pattern in Java to streamline complex object creation. Learn through detailed explanations and examples. Perfect for software developers aiming to enhance code readability and maintainability. Creational en
Code simplification
Domain
Encapsulation
Extensibility
Instantiation
Interface

Also known as

  • Fluent Builder

Intent of Step Builder Design Pattern

The Step Builder pattern in Java is an advanced technique to create complex objects with clarity and flexibility. It is perfect for scenarios requiring meticulous step-by-step object construction.

Detailed Explanation of Step Builder Pattern with Real-World Examples

Real-world example

Imagine a scenario where you are assembling a custom computer. The process involves several steps: selecting the CPU, choosing the motherboard, adding memory, picking a graphics card, and installing storage. Each step builds on the previous one, gradually creating a fully functional computer. This step-by-step assembly process mirrors the Step Builder design pattern, ensuring that each component is correctly chosen and installed in a structured manner, ultimately resulting in a custom-built computer that meets specific requirements and preferences.

In plain words

The Step Builder pattern constructs complex objects incrementally through a series of defined steps, ensuring clarity and flexibility in the creation process.

Wikipedia says

The Step Builder pattern is a variation of the Builder design pattern, designed to provide a flexible solution for constructing complex objects step-by-step. This pattern is particularly useful when an object requires multiple initialization steps, which can be done incrementally to ensure clarity and flexibility in the creation process.

Programmatic Example of Step Builder Pattern in Java

The Step Builder pattern in Java is an extension of the Builder pattern that guides the user through the creation of an object in a step-by-step manner. This pattern improves the user experience by only showing the next step methods available, and not showing the build method until it's the right time to build the object.

Let's consider a Character class that has many attributes such as name, fighterClass, wizardClass, weapon, spell, and abilities.

@Getter
@Setter
public class Character {

  private String name;
  private String fighterClass;
  private String wizardClass;
  private String weapon;
  private String spell;
  private List<String> abilities;

  public Character(String name) {
    this.name = name;
  }

  // toString method omitted
}

Creating an instance of this class can be complex due to the number of attributes. This is where the Step Builder pattern comes in handy.

We create a CharacterStepBuilder class that guides the user through the creation of a Character object.

public class CharacterStepBuilder {

  // Builder steps and methods...

  public static NameStep newBuilder() {
    return new Steps();
  }

  // Steps implementation...
}

The CharacterStepBuilder class defines a series of nested interfaces, each representing a step in the construction process. Each interface declares a method for the next step, guiding the user through the construction of a Character object.

public interface NameStep {
  ClassStep name(String name);
}
public interface ClassStep {
  WeaponStep fighterClass(String fighterClass);
  SpellStep wizardClass(String wizardClass);
}

// More steps...

The Steps class implements all these interfaces and finally builds the Character object.

private static class Steps implements NameStep, ClassStep, WeaponStep, SpellStep, BuildStep {

  private String name;
  private String fighterClass;
  private String wizardClass;
  private String weapon;
  private String spell;
  private List<String> abilities;

  // Implement the methods for each step...

  @Override
  public Character build() {
    return new Character(name, fighterClass, wizardClass, weapon, spell, abilities);
  }
}

Now, creating a Character object becomes a guided process:

public static void main(String[] args) {

    var warrior = CharacterStepBuilder
            .newBuilder()
            .name("Amberjill")
            .fighterClass("Paladin")
            .withWeapon("Sword")
            .noAbilities()
            .build();

    LOGGER.info(warrior.toString());

    var mage = CharacterStepBuilder
            .newBuilder()
            .name("Riobard")
            .wizardClass("Sorcerer")
            .withSpell("Fireball")
            .withAbility("Fire Aura")
            .withAbility("Teleport")
            .noMoreAbilities()
            .build();

    LOGGER.info(mage.toString());

    var thief = CharacterStepBuilder
            .newBuilder()
            .name("Desmond")
            .fighterClass("Rogue")
            .noWeapon()
            .build();

    LOGGER.info(thief.toString());
}

Console output:

12:58:13.887 [main] INFO com.iluwatar.stepbuilder.App -- This is a Paladin named Amberjill armed with a Sword.
12:58:13.889 [main] INFO com.iluwatar.stepbuilder.App -- This is a Sorcerer named Riobard armed with a Fireball and wielding [Fire Aura, Teleport] abilities.
12:58:13.889 [main] INFO com.iluwatar.stepbuilder.App -- This is a Rogue named Desmond armed with a with nothing.

Detailed Explanation of Step Builder Pattern with Real-World Examples

Step Builder

When to Use the Step Builder Pattern in Java

The Step Builder pattern in Java is used

  • When constructing an object that requires multiple initialization steps.
  • When object construction is complex and involves many parameters.
  • When you want to provide a clear, readable, and maintainable way to construct an object in a step-by-step manner.

Step Builder Pattern Java Tutorials

Real-World Applications of Step Builder Pattern in Java

  • Complex configuration settings in Java applications.
  • Constructing objects for database records with multiple fields.
  • Building UI elements where each step configures a different part of the interface.

Benefits and Trade-offs of Step Builder Pattern

Benefits:

  • Improves code readability and maintainability by providing a clear and concise way to construct objects.
  • Enhances flexibility in creating objects as it allows variations in the construction process.
  • Encourages immutability by separating the construction process from the object's representation.

Trade-offs:

  • May result in more complex code due to the additional classes and interfaces required.
  • Can lead to verbose code when many steps are involved.
  • Builder: Both patterns help in constructing complex objects. Step Builder is a variation that emphasizes incremental step-by-step construction.
  • Fluent Interface: Often used in conjunction with the Step Builder pattern to provide a fluent API for constructing objects.
  • Factory Method: Sometimes used with the Step Builder pattern to encapsulate the creation logic of the builder itself.

References and Credits