1.引言
无意间,看到公司的人使用了桥接模式完成了一个功能模块,代码调理清晰,写的很不错。于是有了这篇梳理性文章。
2.正题
2.1 定义
桥接模式顾名思义,需要连接俩端。而且这俩端都需要进行拓展。例如RecycleView的布局,需要viewHolder和layoutManager 俩个维度。俩个维度相互搭配,形成不同的布局。这个时候就需要使用桥接模式。
2.2 UML图
image.pnginterface1,interface2代表俩个维度的抽象。其下有很多实现类
2.3 实例
维度1: IViewHolder 获取不同类型的布局
public interface IViewHolder {
public View onCreateViewHolder();
public void bindViewHolder();
}
维度1 实现的俩个类:
public class TitleViewHolder implements IViewHolder {
public ILayoutManager iLayoutManager;
public TitleViewHolder(ILayoutManager iLayoutManagerImp) {
this.iLayoutManager=iLayoutManagerImp;
}
@Override
public View onCreateViewHolder() {
System.out.println("占据的spansize: "+iLayoutManager.getSpanSize());
return null;
}
@Override
public void bindViewHolder() {
}
}
public class ListViewViewHolder implements IViewHolder {
public ILayoutManager iLayoutManager;
public ListViewViewHolder(ILayoutManager iLayoutManagerImp) {
this.iLayoutManager=iLayoutManagerImp;
}
@Override
public View onCreateViewHolder() {
return null;
}
@Override
public void bindViewHolder() {
}
}
维度2 接口
public interface ILayoutManager {
public int getSpanSize();
public void setWidth(int width);
public void setHeight(int height);
}
实现类:
public class ListViewLayoutManager implements ILayoutManager {
public int width = 0;
public int height = 0;
@Override
public int getSpanSize() {
return 20;
}
@Override
public void setWidth(int width1) {
width = width1;
}
@Override
public void setHeight(int height1) {
height = height1;
}
}
public class TitleLayoutManager implements ILayoutManager {
public int width = 0;
public int height = 0;
@Override
public int getSpanSize() {
return 20;//占据20个spanSize
}
@Override
public void setWidth(int width1) {
width = width1;
}
@Override
public void setHeight(int height1) {
height = height1;
}
}
桥接类:
public class AdapterBridge {
public static void main(String args[]){
ILayoutManager manager=new TitleLayoutManager();
IViewHolder mIViewHolder=new TitleViewHolder(manager);
ILayoutManager manager1=new ListViewLayoutManager();
IViewHolder mIViewHolder1=new ListViewViewHolder(manager);
mIViewHolder.onCreateViewHolder();
}
}
网友评论