MVC:Model-View-Controller 模型-视图-控制
Model模型层处理数据
View用来显示视图
Controller用来控制M和V
M-下载接口
以及结果借口
下载接口的实现类完成下载逻辑实现下载接口重写方法,下载结果传给结果接口
package com.example.mvc;
/**
- 处理数据 M层的第一步接口
- */
public interface GetJsonInterface {
public void getJson(String url);
}
package com.example.mvc;
import android.util.Log;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class GetJsonImpl implements GetJsonInterface{
private static final String TAG = “GetJsonImpl”;
ResultInface resultInface;
public GetJsonImpl(ResultInface resultInface) {
this.resultInface = resultInface;
}
@Override
public void getJson(String url) {
OkHttpClient client = new OkHttpClient.Builder().build();
Request build1 = new Request.Builder().get().url(url).build();
Call call = client.newCall(build1);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
resultInface.fild();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
Log.i(TAG, "onResponse: "+string);
resultInface.success();
}
});
}
}
package com.example.mvc;
public interface ResultInface {
public void success();
public void fild();
}
V,C
去调用下载实现类,传递URL和结果接口
重写接口方法
package com.example.mvc;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
/**
*
- MVC Model-View-Controller 模型视图控制
- Model:模型层用来处理数据
- View:
- Controller
- */
public class MainActivity extends AppCompatActivity implements ResultInface{
private static final String TAG = “MainActivity”;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view) {
GetJsonImpl getJson = new GetJsonImpl(this);
getJson.getJson("https://zhuanlan.zhihu.com//api/columns/growthhacker/posts?limit=10&offset=1");
}
@Override
public void success() {
Log.i(TAG, "success: 我已成功!");
}
@Override
public void fild() {
Log.i(TAG, "fild: ");
}
}