Builder Pattern Config - Problem

Implement a Configuration Builder using the Builder Pattern with a fluent API. The builder should create complex configuration objects with various optional parameters.

Your task is to create a ConfigBuilder class that allows method chaining to set different configuration options. The builder should support setting server host, port, database name, connection timeout, retry attempts, and enable/disable SSL.

Implement the following methods:

  • setHost(host) - Set server host
  • setPort(port) - Set server port
  • setDatabase(dbName) - Set database name
  • setTimeout(seconds) - Set connection timeout
  • setRetries(count) - Set retry attempts
  • enableSSL() - Enable SSL connection
  • build() - Create final configuration object

The final configuration should be returned as a formatted string containing all set values.

Input & Output

Example 1 — Basic Configuration
$ Input: operations = [["setHost", "localhost"], ["setPort", 8080], ["build"]]
Output: Config(host=localhost, port=8080)
💡 Note: Builder sets host to localhost, port to 8080, then builds the configuration string
Example 2 — Full Configuration
$ Input: operations = [["setHost", "server.com"], ["setPort", 3306], ["setDatabase", "mydb"], ["setTimeout", 30], ["enableSSL"], ["build"]]
Output: Config(host=server.com, port=3306, database=mydb, timeout=30, ssl=true)
💡 Note: Builder chains multiple method calls to create a comprehensive configuration
Example 3 — Minimal Configuration
$ Input: operations = [["setDatabase", "testdb"], ["build"]]
Output: Config(database=testdb)
💡 Note: Builder with only database parameter set, demonstrating optional parameter handling

Constraints

  • 1 ≤ operations.length ≤ 10
  • Each operation is either a setter method with parameter or build()
  • String parameters have length ≤ 100
  • Integer parameters are in range [1, 10000]

Visualization

Tap to expand
INPUT OPERATIONSBUILDER PATTERNFINAL RESULTsetHost("localhost")setPort(8080)setDatabase("mydb")enableSSL()build()1Initialize BuilderCreate empty ConfigBuilder2Set Host Parameterbuilder.host = "localhost"3Chain Method CallsEach returns 'this' for chaining4Build ConfigurationGenerate formatted stringConfiguration StringConfig(host=localhost,port=8080,database=mydb,ssl=true)Key Insight:Method chaining creates fluent APIs by returning 'this' from each setter method,allowing complex object construction to read like natural language.TutorialsPoint - Builder Pattern Config | Fluent API Implementation
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 6
32.1K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen