Design Patterns in Ruby | BUILDER
Creational design pattern that allows create complex objects step by step.
Introduction
When you hear the word builder, you probably think of a construction worker however, in this case, we should think of a builder as an object that is able to build new objects based on multiple elements. Imagine a restaurant that sells Tortillas. The owner had the idea that each customer would be able to compose their own tortillas and gave the customers several options to choose from:
- Meat: chicken or mutton
- Vegetables: cucumbers, tomatoes, and onions
- Sauce: mild or spicy
- Spicy sauce has 3 levels: medium, hot, and extra hot
Code Example
So let’s create a Tortilla class that will have attributes such as meat, sauce, and vegetables that will be an array.
In addition, we will create a few empty classes that will be represented by individual ingredients.
We will also add an attribute to a spicy sauce that will determine its level of spiciness.
Now we need to prepare a builder class that will help us create our tortilla.
Now, using the builder class, we want to create a tortilla that will contain:
- Chicken meat
- Two cucumbers
- One Tomato
- Extra spicy sauce
At this point, we have created an interface that allows us to quickly and easily create a new object with freely chosen properties.