Middle
Tell more about the MVP (Model-View-Presenter) pattern.
sobes.tech AI
Answer from AI
MVP divides the application into three interacting components:
- Model: Manages the application's data and business logic. It is independent of the user interface.
- View: Displays data to the user and handles user input. It is passive and contains no decision-making logic.
- Presenter: Acts as an intermediary between Model and View. It receives data from the Model and formats it for the View. It reacts to View events and updates the Model. The View references the Presenter, and the Presenter references the View through an interface.
Advantages of MVP:
- UI change resilience: Logic is in the Presenter, which does not depend on a specific View implementation.
- Testability: The Presenter is easy to test in isolation without mocking the UI.
- Separation of concerns: Clear role separation between components improves maintainability.
Example:
// View Interface
interface MainView {
fun showData(data: String)
fun showError(message: String)
}
// Presenter
class MainPresenter(private val view: MainView, private val model: MainModel) {
fun loadData() {
val data = model.getData()
if (data != null) {
view.showData(data)
} else {
view.showError("Failed to load data")
}
}
}
// Model
class MainModel {
fun getData(): String? {
// Data loading
return "Sample Data"
}
}
// Activity (View Implementation)
class MainActivity : AppCompatActivity(), MainView {
private lateinit var presenter: MainPresenter
private lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView = findViewById(R.id.textView)
val model = MainModel()
presenter = MainPresenter(this, model)
presenter.loadData()
}
override fun showData(data: String) {
textView.text = data
}
override fun showError(message: String) {
textView.text = message
}
}