android MVP 模式記憶體洩漏如何解決
MVP簡介
M-Modle,資料,邏輯操作層,資料獲取,資料持久化儲存。比如網路操作,資料庫操作
V-View,介面展示層,Android中的具體體現為Activity,Fragment
P-Presenter,中介者,連線Modle,View層,同時持有modle引用和view介面引用
示例程式碼
Modle層操作
1234567891011121314151617 | public class TestModle implements IModle{ private CallbackListener callback; public TestModle(CallbackListener callback) { this .callback = callback; } public interface CallbackListener { void onGetData(String data); } public void getData() { new Thread() { public void run() { callback.onGetData( "返回的資料" ); } }.start(); } } |
View層
12345678910111213141516171819202122232425262728 | // 抽象的view層 public interface TestViewInterf extends IView { void onGetData(String data); } // 具體的View層 public class MainActivity extends Activity implements TestViewInterf{ private TestPresenter mTestPresenter; @Override public void onCreate( @Nullable Bundle savedInstanceState) { super .onCreate(savedInstanceState); // view層將獲取資料的任務委派給中介者presenter,並傳入自身例項物件,實現TestViewInterf介面 mTestPresenter = new TestPresenter( this ); mTestPresenter.getData(); } @Override public void onGetData(String data) { // View層只做資料展示 showToast(data); } private void showToast(String toast) { Toast.makeText( this , toast, Toast.LENGTH_LONG).show(); } } |
Presenter中介者
12345678910111213141516171819 | public class TestPresenter implements IPresenter{ IModle modle; IView view; public TestPresenter(IView view) { this .view = view; } public void getData() {
|