Motivation: Constructing objects with many parameters or optional components leads to unwieldy constructors, multiple overloads, hard-to-read call sites, and difficult validation during construction.
Intent: Separate the construction of a complex object from its representation, allowing step-by-step construction.
class HttpRequest private constructor(
val url: String,
val method: String,
val headers: Map<String, String>,
val body: String?,
) {
class Builder(private val url: String) {
private var method = "GET"
private var headers = mutableMapOf<String, String>()
private var body: String? = null
fun method(m: String) = apply { this.method = m }
fun header(k: String, v: String) = apply { headers[k] = v }
fun body(b: String) = apply { this.body = b }
fun build() = HttpRequest(url, method, headers, body)
}
}
// Usage
val request = HttpRequest.Builder("https://api.example.com/users")
.method("POST")
.header("Content-Type", "application/json")
.body("""{"name": "Alice"}""")
.build()