MVC的介紹
MVC是Model-View-Controller的簡稱
Model:模型層,負責處理數據的加載或者存儲
View:視圖層,負責界面數據的展示,與用戶進行交互
Controller:控制器層,負責邏輯業務的處理
爲什麼要用到MVC模式呢?
1、耦合性低。降低了代碼的耦合性,利用MVC框架使得View(視圖)層和Model(模型)層可以很好的分離,這樣就達到了解耦的目的,所以耦合性低,減少模塊代碼之間的相互影響。
2、模塊區域分明,方便開發人員的維護。
package com.example.mvc_day2;
//Medol層的第二步:接口的實現類
import android.util.Log;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
//Medol層的第二步,接口的實現 類
//給接口傳值,調用接口中的方法
public class GetJsonImpl implements GetJsonInterface {
ResultInterface resultInterface;
//傳值
public GetJsonImpl(ResultInterface resultInterface) {
this.resultInterface = resultInterface;
}
@Override
public void getJson(String url) {
OkHttpClient client = new OkHttpClient.Builder().build();
Request request = new Request.Builder().url(url).get().build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
resultInterface.fail();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//成功
String string = response.body().string();
Log.d("json",string);
resultInterface.success(string);
}
});
}
}
接口
package com.example.mvc_day2;
//規定如何處理數據 M層第一步接口
public interface GetJsonInterface {
public void getJson(String url);
}
acivity類
package com.example.mvc_day2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
/*
MVC:Medol-View-Controller 模型-視圖-控制
Model:模型層用來處理數據
View: 用來顯示
Conroller:用來控制M和V
*/
public class MainActivity extends AppCompatActivity implements ResultInterface{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void download(View view) {
//下載的邏輯寫了,在Modle
//顯示 還得和Medol
GetJsonImpl im = new GetJsonImpl(this);
//執行下載的邏輯
im.getJson("https://news-at.zhihu.com/api/4/news/latest");
}
//取值
@Override
public void success(String json) {//去結果,從M層的取的
Log.d("json",json);
}
@Override
public void fail() {
}
}
接口
package com.example.mvc_day2;
public interface ResultInterface {
public void success(String json);
public void fail();
}