Using Builder Pattern in Ruby
By Sandip Parida
The builder pattern is a creational design pattern used for building complex objects involving several steps to create or requiring multiple sub-objects.
The Problem
Consider building a car that requires an engine, body, and wheels. Without the builder pattern, creating different types of cars requires repetitive code that duplicates setup logic across your codebase.
The Solution: Builder Pattern
The pattern uses four components:
- CarBuilder — abstract class defining the building interface
- Director — encapsulates the assembly process
- HatchBackBuilder — concrete builder for hatchbacks
- SuvBuilder — concrete builder for SUVs
How It Works
Creation becomes clean and simple:
builder = HatchBackBuilder.new
director = Director.new
director.set_builder(builder)
hatchback = director.build_car
Want an SUV instead? Just swap the builder:
builder = SuvBuilder.new
director.set_builder(builder)
suv = director.build_car
Extensibility
Adding new requirements — like doors — only requires modifying the Director class once. The change automatically applies across all car types. This separation of concerns keeps your code maintainable as complexity grows.
When to Use the Builder Pattern
- When object creation involves multiple steps
- When you need to create different representations of the same type
- When construction logic should be separated from the object itself
Conclusion
The Builder pattern abstracts away complex instantiation logic, making your code cleaner and more maintainable. It’s particularly valuable when creating objects with many optional parameters or multi-step construction processes.