MVC in Android

Overview

MVC stands for Model-View-Controller. 
The pattern suggests to split the codes into 3 components
  1. View - It's the Activities and Fragments of the application.
  2. Model - A class that stores the application data. It has no knowledge about the View.
  3. Controller - A class that establishes the relation between View and Model. It contains the core application logic and informs the View about the about of Model.
There are two possible ways to apply MVC pattern
  1. Approach 1: Activities and Fragments can perform the role of Controller and are responsible for updating the view.
  2. Approach 2: Use Activity and Fragments as Views and Controller while Model will be a separate class that does not extend any Activity class.

Steps to follow

  • Create a Model class and extend it with Observable() class. The Model class has not information about the View.
 class Model : Observable()
{
private val list : MutableList<Int>

init
{
list = ArrayList(3)
list.add(0)
list.add(0)
list.add(0)
}

@Throws(IndexOutOfBoundsException::class)
fun getValue(theIndex : Int) : Int
{
return list[theIndex]
}

@Throws(IndexOutOfBoundsException::class)
fun setValueAtIndex(theIndex : Int)
{
list[theIndex] = list[theIndex] + 1
setChanged()
notifyObservers()
}
}
  • Define the functionalities of View and Controller in the MainActivity file. As Model is extending and Observer() class, so MainActivity must implement Observer interface.
 class MainActivity : AppCompatActivity() , Observer , View.OnClickListener
{
private lateinit var myModel : Model
override fun onCreate(savedInstanceState : Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
myModel = Model()
myModel.addObserver(this)

btnFirstCount.setOnClickListener(this)
btnSecondCount.setOnClickListener(this)
btnThirdCount.setOnClickListener(this)
}

override fun update(observable : Observable? , argument : Any?)
{
btnFirstCount.text = "Count: ${myModel.getValue(0)}"
btnSecondCount.text = "Count: ${myModel.getValue(1)}"
btnThirdCount.text = "Count: ${myModel.getValue(2)}"
}

override fun onClick(view : View?)
{
when (view?.id)
{
R.id.btnFirstCount -> myModel?.setValueAtIndex(0)
R.id.btnSecondCount -> myModel?.setValueAtIndex(1)
R.id.btnThirdCount -> myModel?.setValueAtIndex(2)
}
}
}

Reference

Comments

Popular posts from this blog

SSLSocketFactory in Android

Architecture Components in Android

DataBinding in Android