MVP实操
理论:
Presenter负责逻辑的处理,Model提供数据,View负责显示
MVP架构模式对于MVC模式主要特点是View 和 Model的完全分离,所有的交互都通过Presenter这个中间者。
优点:
1. model 和 view完全分离,可以修改视图而不影响模型
2. 易于解决内存泄露问题
3. 可以更方便的单元测试
练习:
1,定义一个接口Iview;
public interface Iview { void showToast(); void showList(List<String> list); }
2,写一个model类以获取数据
public class DemoModel { public List getData(){ List<String> list = new ArrayList(); list.add("one"); list.add("two"); list.add("three"); list.add("four"); list.add("five"); return list; } }
3,presenter类得到view和model的引用
public class DemoPresenter { Iview view; DemoModel model; public DemoPresenter(DemoModel demoModel){ model = demoModel; } public void attach(Iview view){ this.view = view; } public void detache(){ this.view = null; } public void fetch(){ List data = model.getData(); view.showList(data); view.showToast(); } }
4.Activity实现Iview
class MainActivity : AppCompatActivity(), Iview { lateinit var mListView:ListView var mDemoPresenter:DemoPresenter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mDemoPresenter = DemoPresenter(DemoModel()) mDemoPresenter?.attach(this) initView() mDemoPresenter?.fetch() } private fun initView() { mListView = findViewById<ListView>(R.id.mListView) } override fun showToast() { Toast.makeText(this,"ok",Toast.LENGTH_SHORT).show() } override fun showList(list: MutableList<String>?) { mListView.adapter = ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list) } override fun onDestroy() { mDemoPresenter?.detache() mDemoPresenter = null super.onDestroy() } }
5,在Activity中实例一个Presenter与之绑定,绑定后通过presenter对象调用fetch()来获取数据并显示。