什么是MVP?
先来分享下,我对MVP架构的理解,如果有不正确的地方,请提出来,我一定改正。
看了很多文章之后,我认为:M代指Model,V代指Activity,P代指Presenter。下面详细说明:
Google在某个项目Demo中用了上述那种结构,从而被大多数人接收并推广,原地址:【https://github.com/googlesamples/android-architecture/tree/todo-mvp】,在推广过程中,有很多个版本,各自都有各自的说法,但是Goole却没有明确说明,这也并不影响MVP这个架构模式的使用和推广,而我比较赞同Goole的那种做法的,一个功能或者模块一个Package,M作为储存数据的仓库的,Goole给出的Demo中,由于数据只是样例,所以把Model作为公用,P(Presenter)用来管理M和V。
AppLib中MVP是怎么设计的?
为了方便,我们约定M用IModel,V用IView,P用IPresenter,并用Base*进行封装出来,你可以通过继承的方式来使用M、V、P。当然你也可以用IModel来指代M,IView指代V,IPresenter指代P。
M作为存放数据的仓库,我们给出了接口(IRepsoitoryManager)交由使用者实现,可以用来请求网络数据,数据缓存,数据处理等等。
Activity方面,我们仍然用Base*进行封装。需要注意的是,BaseActivity继承AppCompatActivity(),不再继承Activity(),当然AppLib中的AppManager还是支持Activity()
将MVP模块存放到mvp,方便源码阅读。
使用示例
在介绍MVP使用之前,我们推荐你这样做:
1、重写Application,并继承AppLib中的BaseApplication(),这样你就可以使用Debug,但你需要在
Application
中开启:
class APP : BaseApplication() {
override fun onCreate() {
super.onCreate()
isDebug = true
}
}
记得要使用
2、实现 IRepositoryManager
:
class RepositoryManager : IRepositoryManager {
override fun onDestroy() {
}
override fun getNetData(url : String, params : Any, callBack : ICallback<Any>) {
}
}
特别提醒,虽然参数设为Any,但并不代表可以提交任何格式的数据,虽然也是可以的,但我们并推荐那么做。
3、下面以登录为例,实现MVP的代码,当然这代码是可以通用的,命名也是为了这么做:
class LoginMVP {
class Activity : BaseActivity<Presenter>(), IView {
override fun initFragment() = null
override fun isUseFragment() = false
override fun initPresenter() = Presenter()
override fun getLayoutId() = R.layout.activity_login
// click events
override fun click() {
// TODO
}
override fun init() {
// mPresenter为Presenter对象,用来操作Prensenter,你可以直接使用
toast(mPresenter.tipText())
log("Hello iWenyi") // Debug模式,需要在Application中开启,TAG默认为iWenyi,暂不支持修改
}
}
class Presenter : BasePresenter<Model, Activity>() {
fun tipText() = "Hello iWenyi"
}
class Model : BaseModel(RepositoryManager()) {
}
class Fragment : BaseFragment() {
override fun init() {
}
}
}
4、注册一下吧:
<application
android:name=".APP"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".login.LoginMVP$Activity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
5、引入:
allprojects {
repositories {
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
compile 'com.github.fengwenyi:AppLib:0.0.9'
// gson
compile 'com.google.code.gson:gson:2.8.1'
}
示例代码只是样例,并不能代码AppLib中MVP的全部内容。