Created
March 5, 2020 10:57
-
-
Save pfieffer/a3fbd4ac80c2d3ba64887517ae513eb0 to your computer and use it in GitHub Desktop.
Builder Pattern demo for a model class in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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