Milliseid lähenemisviise kasutada, et vältida otse funktsiooni eksemplari loomist koodis?
sobes.tech AI
Vastus AI-lt
To avoid directly creating an instance of a function (for example, an object or class) in the code, the following approaches are used:
-
Factory Method — creates objects through special methods, hiding the creation details.
-
Dependency Injection — objects are passed into the class from outside, usually via constructor or setter, making replacement and testing easier.
-
Using interfaces and abstractions — code works with interfaces, and specific implementations are created and passed from outside.
-
Lambda expressions and functional interfaces — instead of creating new classes, functions can be passed as parameters.
Example with dependency injection in Android (Kotlin):
interface ClickHandler {
fun onClick()
}
class MyActivity(private val clickHandler: ClickHandler) {
fun setup() {
// Use the passed handler instead of creating a new one
button.setOnClickListener { clickHandler.onClick() }
}
}
This approach increases code flexibility and testability, and also facilitates maintenance and extension.