Middle
Šta je obrazac dizajna Factory i kako se koristi u izgradnji objekata (Builder)?
sobes.tech АИ
Одговор од АИ
Модел Factory Method пружа интерфејс за креирање објеката у основној класи, омогућавајући подкласи да мењају тип креираних објеката. ConcreteFactory одлучује који ConcreteProduct ће креирати.
Builder одваја конструисање сложеног објекта од његове презентације. Он омогућава креирање објекта корак по корак, пружајући различите методе за постављање својстава и враћајући готови објекат. Користи се када објекат има много опционих параметара и његово креирање захтева сложену логику.
Фабрика креира целе објекте, а Творилац их креира деловима.
Пример:
// Factory Method
interface Dialog {
fun createButton(): Button
fun render() {
val okButton = createButton()
okButton.render()
}
}
class WindowsDialog : Dialog {
override fun createButton(): Button {
return WindowsButton()
}
}
class WebDialog : Dialog {
override fun createButton(): Button {
return HTMLButton()
}
}
interface Button {
fun render()
fun onClick()
}
class WindowsButton : Button {
override fun render() {
println("Rendering Windows button")
}
override fun onClick() {
println("Clicking Windows button")
}
}
class HTMLButton : Button {
override fun render() {
println("Rendering HTML button")
}
override fun onClick() {
println("Clicking HTML button")
}
}
// Builder
class Pizza private constructor(
private val size: String,
private val cheese: Boolean,
private val pepperoni: Boolean,
private val mushrooms: Boolean
) {
data class Builder(
var size: String = "medium",
var cheese: Boolean = false,
var pepperoni: Boolean = false,
var mushrooms: Boolean = false
) {
fun size(size: String) = apply { this.size = size }
fun cheese(cheese: Boolean) = apply { this.cheese = cheese }
fun pepperoni(pepperoni: Boolean) = apply { this.pepperoni = pepperoni }
fun mushrooms(mushrooms: Boolean) = apply { this.mushrooms = mushrooms }
fun build() = Pizza(size, cheese, pepperoni, mushrooms)
}
override fun toString(): String {
return "Pizza(size='$size', cheese=$cheese, pepperoni=$pepperoni, mushrooms=$mushrooms)"
}
}
// Using Builder
val pizza = Pizza.Builder()
.size("large")
.cheese(true)
.pepperoni(true)
.build()
println(pizza)
Comparison:
| Characteristic | Factory Method | Builder |
|---|---|---|
| Purpose | Creating objects via subclasses. | Step-by-step creation of complex objects. |
| Object complexity | Usually simple objects. | Complex objects with multiple parameters. |
| Creation flexibility | Choice of object type depending on subclass. | Incremental setting of object properties. |
| Object return | Returns a finished object. | Returns a finished object after construction. |
| Application | Frameworks, libraries, where object type is unknown at compile time. | Objects with many optional parameters. |