Android MVC MVP MVVM

Posted noigel

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android MVC MVP MVVM 相关的知识,希望对你有一定的参考价值。

MVP模型

 

 View主要是Activity,Fragment

MVP和MVC的差别

1.Model和View不再直接通信,通过中间层Presenter来实现。

2.Activity的功能被简化,不再充当控制器,主要负责View层面的工作。

 

 

 

 

 MVPPresenter

public class MVPPresenter {
    private IMVPView view;
    private MVPModel model;

    public MVPPresenter(IMVPView view) {
        this.view=view;
        model=new MVPModel();
    }

    public void getData(String accountName) {
        model.getAccountData(accountName, new ResultCallback() {
            @Override
            public void onSuccess(Account account) {
                view.showSuccessPage(account);
            }

            @Override
            public void onFailure() {
                view.showFailurePage();
            }
        });
    }

}

IMVPView

public interface IMVPView {
    String getUserInput();

    void showSuccessPage(Account account);

    void showFailurePage();
}

MVPModel

public class MVPModel {
    public void getAccountData(String accountName, ResultCallback cb) {
        Random random=new Random();
        boolean isSuccess=random.nextBoolean();
        if (isSuccess) {
            Account account = new Account();
            account.setName(accountName);
            account.setLevel(100);
            cb.onSuccess(account);
        } else {
            cb.onFailure();
        }
    }
}

MVPActivity

public class MVPActivity extends AppCompatActivity implements IMVPView{
    private TextView tvResult;
    private EditText etAccount;
    private MVPPresenter presenter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
        tvResult = findViewById(R.id.tvResult);
        etAccount = findViewById(R.id.etAccount);
        presenter = new MVPPresenter(this);
    }

    public void ButtonClick(View view) {
        presenter.getData(getUserInput());
    }


    @Override
    public String getUserInput() {
        return etAccount.getText().toString();
    }

    @Override
    public void showSuccessPage(Account account) {
        tvResult.setText("用户账号: "+account.getName()+ " | "+"用户等级: "+account.getLevel());
    }

    @Override
    public void showFailurePage() {
        tvResult.setText("获取数据失败");
    }
}

 

以上是关于Android MVC MVP MVVM 的主要内容,如果未能解决你的问题,请参考以下文章

Android 中 MVC、MVP 和 MVVM 对比

Android App的设计架构:MVC,MVP,MVVM与架构经验谈

Android MVP-编程思想1(什么是MVC-MVP-MVVM模式?)

Android MVC MVP MVVM

Android中MVC、MVP、MVVM的区别与使用

Android中的MVC,MVP和MVVM