Skip to content

Instantly share code, notes, and snippets.

@pfieffer
Created March 5, 2020 10:57
Show Gist options
  • Save pfieffer/a3fbd4ac80c2d3ba64887517ae513eb0 to your computer and use it in GitHub Desktop.
Save pfieffer/a3fbd4ac80c2d3ba64887517ae513eb0 to your computer and use it in GitHub Desktop.
Builder Pattern demo for a model class in Kotlin
class Laptop(builder: Builder) {
private val processor: String = builder.processor
private val ram: String = builder.ram
private val battery: String = builder.battery
private val screenSize: String = builder.screenSize
// Builder class
class Builder(processor: String) {
var processor: String = processor // this is necessary
// optional features
var ram: String = "2GB"
var battery: String = "5000MAH"
var screenSize: String = "15inch"
fun setRam(ram: String): Builder {
this.ram = ram
return this
}
fun setBattery(battery: String): Builder {
this.battery = battery
return this
}
fun setScreenSize(screenSize: String): Builder {
this.screenSize = screenSize
return this
}
fun create(): Laptop {
return Laptop(this)
}
}
}
/**
*Using the above code
**/
Laptop.Builder("i7") // processor is compulsory
.setRam("8GB") // this is optional
.setBattery("6000MAH") // this is optional
.create()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment