개발/Android
[Kotlin/코드] MVP (2)
레란희
2022. 2. 14. 14:43
이전에 했던 코드(https://relz.tistory.com/64)에서 테스트용으로 넣었던 저장&불러오기를 없애고
사칙연산 버전으로 변경하였음
1. Contract
package com.monkey.mvpstudy
interface Contract {
interface View {
fun setValue(num1: Int, num2: Int, num3: Int)
fun showResult(num: Int)
}
interface Presenter {
fun getSum(num1: Int, num2: Int)
fun getSubtract(num1: Int, num2: Int)
fun getMultiply(num1: Int, num2: Int)
fun getDivide(num1: Int, num2: Int)
}
}
2. MainModel
class MainModel {
var num1 = 0
var num2 = 0
fun plus() : () -> Int = { num1 + num2 }
fun subtract() : () -> Int = { num1 - num2 }
fun multiply() : () -> Int = { num1 * num2 }
fun divide() : () -> Int = { num1 / num2 }
}
3. MainActivity
package com.monkey.mvpstudy
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.monkey.mvpstudy.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity(), Contract.View, View.OnClickListener {
private val binding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val presenter by lazy {
MyPresenter(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.btnSum.setOnClickListener(this)
binding.btnSubtract.setOnClickListener(this)
binding.btnMultiply.setOnClickListener(this)
binding.btnDivide.setOnClickListener(this)
}
override fun setValue(num1: Int, num2: Int, num3: Int) {
binding.etNum1.setText(num1.toString())
binding.etNum2.setText(num2.toString())
showResult(num3)
}
override fun showResult(num: Int) {
binding.tvResult.text = num.toString()
}
override fun onClick(v: View?) {
val num1 = binding.etNum1.text.toString().toInt()
val num2 = binding.etNum2.text.toString().toInt()
when(v) {
binding.btnSum -> presenter.getSum(num1, num2)
binding.btnSubtract -> presenter.getSubtract(num1, num2)
binding.btnMultiply -> presenter.getMultiply(num1, num2)
binding.btnDivide -> presenter.getDivide(num1, num2)
}
}
}
4. MyPresent
package com.monkey.mvpstudy
class MyPresenter : Contract.Presenter {
private var view : Contract.View
private var model : MainModel
constructor(view: Contract.View) {
this.view = view
this.model = MainModel()
}
override fun getSum(num1: Int, num2: Int) {
val result = calculate(num1, num2, model.plus())
view.showResult(result)
}
override fun getSubtract(num1: Int, num2: Int) {
val result = calculate(num1, num2, model.subtract())
view.showResult(result)
}
override fun getMultiply(num1: Int, num2: Int) {
val result = calculate(num1, num2, model.multiply())
view.showResult(result)
}
override fun getDivide(num1: Int, num2: Int) {
val result = calculate(num1, num2, model.divide())
view.showResult(result)
}
private fun calculate(num1: Int, num2: Int, calc: () -> Int): Int {
model.num1 = num1
model.num2 = num2
return calc()
}
}