What is this pattern for?
This pattern is used when it’s necessary to isolate the construction of a complex object and at the same time have more than one representation.
Featuring:
The Client:
They want an application with a specific construction. In this case, they want an application written in Kotlin.
The Director:
This person knows the application parts and the requisites from the client, but he or she doesn’t know how to do it.
The Developers:
The team follows the Director’s indications to deliver an application to the Client. Each of them has a specific technical knowledge, in this case, a programming language.
The model:
The code:
class Director(val developer: Developer){
fun orderCreateApplication() {
developer.createDatabase()
developer.createBackend()
developer.createUserInterface()
}
}
open class Developer {
open fun createDatabase() {}
open fun createBackend() {}
open fun createUserInterface() {}
open fun deliverApplication(): String? { return null}
}
class JavaDeveloper(): Developer() {
override fun createBackend() {
println("[Java developer] Backend created!")
}
override fun createUserInterface() {
println("[Java developer] User Interface created!")
}
override fun createDatabase() {
println("[Java developer] Database created!")
}
override fun deliverApplication(): String {
return "Here you go! Your Java Application."
}
}
class KotlinDeveloper : Developer() {
override fun createBackend() {
println("[Kotlin developer] Backend created!")
}
override fun createUserInterface() {
println("[Kotlin developer] User Interface created!")
}
override fun createDatabase() {
println("[Kotlin developer] Database created!")
}
override fun deliverApplication(): String {
return "Here you go! Your Kotlin Application."
}
}
class ScalaDeveloper : Developer() {
override fun createBackend() {
println("[Scala developer] Backend created!")
}
override fun createUserInterface() {
println("[Scala developer] User Interface created!")
}
override fun createDatabase() {
println("[Scala developer] Database created!")
}
override fun deliverApplication(): String {
return "Here you go! Your Scala Application."
}
}
The pattern in action:
The Sequence Diagram:
The code:
fun main(args: Array<String>) {
// The client wants an application written in Kotlin
val circleTheDeveloper = KotlinDeveloper()
// The director instructs the developer with client's requisites
val pentagonTheDirector = Director(squareTheDeveloper)
pentagonTheDirector.orderCreateApplication()
// The developer delivers the result
val applicationResult = squareTheDeveloper.deliverApplication()
println(applicationResult)
}
[Kotlin developer] Database created!
[Kotlin developer] Backend created!
[Kotlin developer] User Interface created!
Here you go! Your Kotlin Application.
Process finished with exit code 0