单一职责之ImageLoader(一)

前端之家收集整理的这篇文章主要介绍了单一职责之ImageLoader(一)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

单一职责原则
一个类应该只有一个引起变化的原因,也就是类中的成员方法,字段都是息息相关的,将相关性不高的部分抽象,
独立出来。

  1. public class ImageLoader {
  2. //图片缓存
  3. LruCache<String,Bitmap> mImageCache;
  4. //线程池
  5. ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().
  6. availableProcessors());
  7. public ImageLoader(){
  8. initImageCache();
  9. }
  10. private void initImageCache(){
  11. //计算可用的最大内存
  12. final int maxMemory = (int)(Runtime.getRuntime().maxMemory()/1024);
  13. //取四分之一内存作为缓存
  14. final int cacheSize = maxMemory/4;
  15. mImageCache = new LruCache<String,Bitmap>(cacheSize){
  16. @Override
  17. protected int sizeOf(String key,Bitmap value) {
  18. return value.getRowBytes()*value.getHeight()/1024;
  19. }
  20. };
  21. }
  22.  
  23. //显示网络加载的图片 调用一次都会开启线程去下载 并且显示
  24. public void displayImage(final String url,final ImageView imageView){
  25. imageView.setTag(url);
  26. mExecutorService.submit(new Runnable() {
  27. @Override
  28. public void run() {
  29. Bitmap bitmap = downloadImage(url);
  30. if(bitmap == null){
  31. return ;
  32. }
  33. if(imageView.getTag().equals(url)){
  34. imageView.setImageBitmap(bitmap);
  35. }
  36. mImageCache.put(url,bitmap);
  37. }
  38. });
  39. }
  40.  
  41. public Bitmap downloadImage(String imageUrl){
  42. Bitmap bitmap = null;
  43. try {
  44. URL url = new URL(imageUrl);
  45. final HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  46. bitmap = BitmapFactory.decodeStream(conn.getInputStream());
  47. conn.disconnect();
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. }
  51. return bitmap;
  52. }
  53. }

ImageLoader 类中其中 imagecache 可以作为单独模块抽象出来,作为ImageLoader 一个组合的模块,这样拓展起来 可以很方便

猜你在找的设计模式相关文章