什么叫抽象依赖于第三方框架?就是降低我们对具体某个框架的依赖性,从而方便我们快速切换到不同的框架去。
比如最常用到的图片加载框架,假如现在用的是Android-Universal-Image-Loader这个框架。
然后在任何需要加载图片的地方写上下面这样的代码段。
ImageLoader.getInstance().displayImage(imageUrl,imageView);
如果我有几十上百个地方都这么写,而在某一天,突然要求换成Glide这个框架,然后你就需要丧心病狂的去改动几十上百个地方的代码,不仅工作量大,而且还容易出错。
正确的方式,应该是对框架做一个抽象的封装,以应对未来发生的变化。
针对图片加载框架,先写一个接口,实现图片加载用常用到的方法(大部份时候只是显示网络图片)
public interface ImageLoader {
void init(Context context);
void displayImage(String uri, ImageView imageView);
}
上面接口只是最简单的图片加载功能,可以根据需要扩展。
接着用Android-Universal-Image-Loader实现此接口
public class UILImageLoader implements ImageLoader {
@Override
public void init(Context context) {
...
}
@Override
public void displayImage(String uri, ImageView imageView) {
com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(uri,imageView);
}
}
然后写一个工厂类
public class ImageLoaderManager {
private static ImageLoader imageLoader;
public static ImageLoader getImageLoader(Context context) {
if (imageLoader == null) {
synchronized (ImageLoaderManager.class) {
if (imageLoader == null) {
imageLoader = new UILImageLoader();
imageLoader.init(context);
}
}
}
return imageLoader;
}
}
在所有加载图片的地方这样用:
ImageLoaderManager.getImageLoader(context).displayImage(uri, imageView);
接下来,要换Glide框架了。只需要用Glide实现ImageLoader接口
public class GlideImageLoader implements ImageLoader {
private Context context;
@Override
public void init(Context context) {
this.context = context.getApplicationContext();
}
@Override
public void displayImage(String uri, ImageView imageView) {
Glide.with(context).load(uri).into(imageView);
}
}
然后修改ImageLoaderManager
public class ImageLoaderManager {
private static ImageLoader imageLoader;
public static ImageLoader getImageLoader(Context context) {
if (imageLoader == null) {
synchronized (ImageLoaderManager.class) {
if (imageLoader == null) {
// imageLoader = new UILImageLoader();
imageLoader = new GlideImageLoader();
imageLoader.init(context);
}
}
}
return imageLoader;
}
}
是不是很简单?
同理,网络请求框架也可以这样以抽象接口的形式来封装!降低对第三方框架的依赖。
网友评论