单一职责原则
一个类应该只有一个引起变化的原因,也就是类中的成员方法,字段都是息息相关的,将相关性不高的部分抽象,
独立出来。
- public class ImageLoader {
- //图片缓存
- LruCache<String,Bitmap> mImageCache;
- //线程池
- ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().
- availableProcessors());
- public ImageLoader(){
- initImageCache();
- }
- private void initImageCache(){
- //计算可用的最大内存
- final int maxMemory = (int)(Runtime.getRuntime().maxMemory()/1024);
- //取四分之一内存作为缓存
- final int cacheSize = maxMemory/4;
- mImageCache = new LruCache<String,Bitmap>(cacheSize){
- @Override
- protected int sizeOf(String key,Bitmap value) {
- return value.getRowBytes()*value.getHeight()/1024;
- }
- };
- }
-
- //显示网络加载的图片 调用一次都会开启线程去下载 并且显示
- public void displayImage(final String url,final ImageView imageView){
- imageView.setTag(url);
- mExecutorService.submit(new Runnable() {
- @Override
- public void run() {
- Bitmap bitmap = downloadImage(url);
- if(bitmap == null){
- return ;
- }
- if(imageView.getTag().equals(url)){
- imageView.setImageBitmap(bitmap);
- }
- mImageCache.put(url,bitmap);
- }
- });
- }
-
- public Bitmap downloadImage(String imageUrl){
- Bitmap bitmap = null;
- try {
- URL url = new URL(imageUrl);
- final HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- bitmap = BitmapFactory.decodeStream(conn.getInputStream());
- conn.disconnect();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return bitmap;
- }
- }
ImageLoader 类中其中 imagecache 可以作为单独模块抽象出来,作为ImageLoader 一个组合的模块,这样拓展起来 可以很方便