MVP的核心思想:原来的UI逻辑都抽象成一个View接口,业务逻辑抽象成precenter接口,model还是原来的model。model把数据返回给precenter,precenter再把数据返回给view,每个view都对应着一个precener,model可能是共用的。
实体类Girl
public class Girl {
public int icon;
public String like;
public String style;
public Girl() {
}
public Girl(int icon, String like, String style) {
super();
this.icon = icon;
this.like = like;
this.style = style;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
public String getLike() {
return like;
}
public void setLike(String like) {
this.like = like;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
}
model操作相关类
IGirlModel.java
public interface IGirlModel {
//加载返回数据
void loadGirl(GrilOnLoadListener grilOnLoadListener);
//返回数据
interface GrilOnLoadListener {
void onComplete(List<Girl> list);
}
}
IGirlModelImpl.java
public class IGirlModelImpl implements IGirlModel{
//加载返回数据
@Override
public void loadGirl(GrilOnLoadListener grilOnLoadListener) {
//这里模拟网络请求
List<Girl> data = new ArrayList<Girl>();
data.add(new Girl(R.drawable.f1, "*****", "123潮流女个性字母印花无袖露脐上衣"));
data.add(new Girl(R.drawable.f2, "231412星", "迷依诗诺夏天新款韩版女装性感夜店欧美风字母印花牛仔露脐背心上衣"));
data.add(new Girl(R.drawable.f3, "五颗星", "迷依诗诺春夏欧美新款性感女装单排扣牛仔背心露脐上衣"));
grilOnLoadListener.onComplete(data);
}
}
present操作类
GirlPrecenter.java
public class GirlPrecenter<T extends IGirlView> {
//View的引用,这里使用弱引用,弱引用在内存不足的时候进行回收
WeakReference<T> mView;
//model层的引用
IGirlModel girlModel = new IGirlModelImpl();
public GirlPrecenter(T view){
this.mView = new WeakReference<T>(view);
}
//执行UI逻辑处理
public void fetch(){
if(mView!=null && girlModel!=null){
girlModel.loadGirl(new IGirlModel.GrilOnLoadListener() {
@Override
public void onComplete(List<Girl> list) {
mView.get().showGirls(list);
}
});
}
}
}
view操作相关类
MainActivity.java
public class MainActivity extends AppCompatActivity implements IGirlView {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listview);
new GirlPrecenter<>(this).fetch();
}
@Override
public void showGirls(List<Girl> girl) {//在这里接收返回数据(如网络请求,数据库操作等等)
listView.setAdapter(new GirlAdapter(this,girl));
}
}
网友评论