Builder Pattern Section9 10
Builder Pattern Section9 10
• Builder Solution:
Use a RequestBuilder class that provides fluent methods to set query parameters, headers,
body content, and authentication details. For example:
RequestBuilder builder;
builder.setMethod("POST")
.setUrl("https://api.example.com/data")
.addHeader("Authorization", "Bearer token")
.addQueryParam("filter", "active")
.setJsonBody(payload)
.build();
This pattern separates request configuration from the client code, ensuring clarity and
fewer mistakes.
• Builder Solution:
Implement a DashboardWidgetBuilder that allows chaining of methods for setting
sections, data sources, styling options, and event callbacks. In React (JavaScript), for
example:
const widget = new DashboardWidgetBuilder()
.setTitle('User Metrics')
.setDataEndpoint('/api/user/metrics')
.addSection('Charts', chartsConfig)
.addSection('Logs', logsConfig)
.setTheme('dark')
.build();
The builder returns a configured React component, improving readability and reusability.
• Builder Solution:
Use a NotificationBuilder class in a native Android app (Java/Kotlin) or cross-platform
framework (e.g., Flutter) that allows:
NotificationBuilder builder = new NotificationBuilder(context)
.setTitle("New Message")
.setBody("You have a new message from John")
.setPriority(NotificationPriority.HIGH)
.addData("conversation_id", "12345")
.setSound("default")
.setChannel("messages");
Notification notification = builder.build();
The Notification object can then be sent via Firebase or local system, keeping configuration
code concise.
• Builder Solution:
Introduce a QueryBuilder class that provides methods to add filters, sorting rules,
pagination, and joins:
QueryBuilder qb = new QueryBuilder("users");
qb.select("id", "name", "email")
.where("age > ?", age)
.andWhere("status = ?", "active")
.orderBy("created_at", "DESC")
.limit(20)
.offset(40);
String sql = qb.build();
This pattern prevents SQL injection by parameterization and improves readability.
10. Quiz: Builder Pattern
1. Which of the following best describes the main purpose of the Builder Pattern?
A. To define a family of algorithms, encapsulate each one, and make them interchangeable.
B. To allow construction of complex objects step by step while keeping the construction
code separate.
D. To ensure that a class has only one instance and provide a global point of access to it.
A. It defines the abstract interface for creating parts of the Product object.
B. When object construction requires multiple optional parameters and the process
should be immutable.
4. In C++, how would you typically implement a builder method for setting a value to an
attribute 'name' of a Product class?
5. Which of the following is NOT a typical advantage of using the Builder Pattern?
6. In a mobile app context, which of the following is a valid use of the Builder Pattern?