Android MVP模式简单例子

MVP模式就是M(Model)、V(View)和P(Presenter)

Model就是数据,怎样获得数据、数据的类型都属于Model,总之就是所以跟数据有关的类和操作都属于Model

View就是展示给用户的界面,包括各种控件、处理点击事件都属于View,在Android中,往往Activity、Fragment都属于View

Presenter就是一个中介,View不直接操作数据,而是通过调用Presenter来间接操纵数据。

 

下面来看个例子:

Android MVP模式简单例子_第1张图片

首先MVP的每一个都需要相应定义接口来说明需要实现的功能,然后都需要实现相应的接口。

 

整体的思路是,Network、MainActivity和PresenterComl需要实现对应接口

PresenterComl中有Network的对象和IView的接口实例,在PresenterComl的请求网络的接口方法中调用Network请求网络的接口方法,然后在里面通过IView实现接口回调,让数据传输给MainActivity

 

Network:

public class Network implements IModel{


    @Override
    public void request(String url,Callback callback) {
        OkHttpClient okHttpClient=new OkHttpClient.Builder().build();
        final Request request=new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(callback);
    }
}

 

PresenterComl:

public class PresenterComl implements IPresenter {
    Network network;
    IView view;
    Handler handler = new Handler(Looper.getMainLooper());
    public PresenterComl(IView view) {
        network = new Network();
        this.view = view;
    }
    @Override
    public void requestData(String url) {
        network.request(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        view.onFailed();
                    }
                });
            }
            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String s = response.body().string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        view.onSuccess(s);
                    }
                });
            }
        });
    }
}

 

MainActivity:

public class MainActivity extends AppCompatActivity implements IView, View.OnClickListener {

    private Button mBtn;
    private TextView mTxt;
    private IPresenter mPresent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtn = findViewById(R.id.btn);
        mTxt = findViewById(R.id.txt);
        mBtn.setOnClickListener(this);

        mPresent = new PresenterComl(this);
    }
    @Override
    public void onSuccess(String message) {
        mTxt.setText("成功接收消息:\n" + message);
    }
    @Override
    public void onFailed() {
        mTxt.setText("接收失败");
    }
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn) {
            mPresent.requestData("https:www.baidu.com");
        }
    }
}

 

你可能感兴趣的:(大学作业)