0% found this document useful (0 votes)
2 views4 pages

Builder Pattern Section9 10

The document discusses the Builder Pattern's application in web and mobile development, highlighting its effectiveness in managing complexity and improving maintainability through real-world examples. It includes scenarios such as constructing complex HTTP requests, building UI components, configuring push notifications, and assembling database queries. Additionally, the document features a quiz to test understanding of the Builder Pattern's principles and applications.

Uploaded by

Kiên Vũ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

Builder Pattern Section9 10

The document discusses the Builder Pattern's application in web and mobile development, highlighting its effectiveness in managing complexity and improving maintainability through real-world examples. It includes scenarios such as constructing complex HTTP requests, building UI components, configuring push notifications, and assembling database queries. Additionally, the document features a quiz to test understanding of the Builder Pattern's principles and applications.

Uploaded by

Kiên Vũ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

9.

Other Real-World Problems and Application in Web and Mobile


Development
Below are examples of real-world scenarios in web and mobile development where the
Builder Pattern (or similar design patterns) helps manage complexity and improve
maintainability.

Example 9.1: Constructing Complex HTTP Requests (Web)


• Real-World Problem:
When integrating with third-party APIs in a web application, developers often need to
build HTTP requests with multiple optional parameters, headers, authentication tokens,
and complex payloads. Manually assembling these requests leads to error-prone code and
poor readability.

• 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.

Example 9.2: Building UI Components (Web)


• Real-World Problem:
Complex user interface components (e.g., a multi-section dashboard widget) in modern
web frameworks require various optional settings (styles, event handlers, data bindings).
Embedding configuration directly in markup or procedural code can become unwieldy.

• 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.

Example 9.3: Configuring Push Notifications (Mobile)


• Real-World Problem:
Mobile apps require elaborate push notification payloads: title, message, data payload,
priority, sound, and platform-specific settings (Android vs. iOS). Managing variants in code
can get confusing.

• 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.

Example 9.4: Assembling Database Queries with Optional Filters (Web/Mobile)


• Real-World Problem:
Applications often need to build SQL or NoSQL queries with multiple optional filters based
on user input (e.g., search forms). Naive string concatenation can lead to syntax errors, SQL
injection risks, and unreadable code.

• 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.

C. To provide an interface for creating families of related or dependent objects without


specifying their concrete classes.

D. To ensure that a class has only one instance and provide a global point of access to it.

2. In the Builder Pattern, what is the role of the Director class?

A. It defines the abstract interface for creating parts of the Product object.

B. It implements the steps to build the Product using a Builder instance.

C. It stores the final Product and returns it to the client.

D. It provides default implementations for builder methods.

3. Which scenario is most suitable for applying the Builder Pattern?

A. When you need to define a skeleton of an algorithm with varying steps.

B. When object construction requires multiple optional parameters and the process
should be immutable.

C. When you need to decouple an abstraction from its implementation.

D. When you want to ensure an object's initialization is controlled by a single global


instance.

4. In C++, how would you typically implement a builder method for setting a value to an
attribute 'name' of a Product class?

A. ProductBuilder setName(const std::string &name) { this->name = name; return *this; }

B. ProductBuilder& setName(const std::string &name) { this->name = name; return *this; }

C. void setName(const std::string &name) { product.name = name; }

D. ProductBuilder setName(std::string name) { product.name = std::move(name); return


*this; }

5. Which of the following is NOT a typical advantage of using the Builder Pattern?

A. Separation of construction and representation of an object.


B. Improved readability when creating complex objects.

C. Elimination of the need for a Director class.

D. Ease of adding new types of representations for the object.

6. In a mobile app context, which of the following is a valid use of the Builder Pattern?

A. Building a complex UI dialog with several optional buttons and fields.

B. Implementing data binding between UI components and a ViewModel.

C. Managing lifecycle events of an Activity or ViewController.

D. Serializing an object to JSON for network transmission.

You might also like