面向对象设计6大原则,单一职责原则,表达的就是“单一”这2个字,不同的功能要放在不同的类中,既可以避免代码复杂过多,而且可以增强代码的可维护性,这是优化代码的第一步,也是很重要的一步。下午写了一个小程序,代码如下:
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.LruCache;
import android.widget.ImageView;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by yangshin99 on 16/2/12.
* 图片加载类,
*/
public class ImageLoader {
//图片缓存
ImageCache mImageCache = new ImageCache();
//线程池,线程数量为CPU的数量
ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
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;
}
}
import android.graphics.Bitmap;
import android.util.LruCache;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by yangshin99 on 16/2/12.
* 图片缓存类
*/
public class ImageCache {
//图片缓存
LruCache<String,Bitmap> mImageCache;
//线程池,线程数量为CPU的数量
ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
public ImageCache(){
initImageCache();
}
private void initImageCache() {
//计算可使用的最大内存
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 2014);
//取四分之一的可用内存作为缓存,
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 put(String url, Bitmap bitmap){
mImageCache.put(url,bitmap);
}
public Bitmap get(String url){
return mImageCache.get(url);
}
}
如上,总共2个类,第一个是图片加载类,实现图片的设置显示和下载,第二个类是图片缓存类,图片加载和图片缓存是不一样的功能,对于不一样的功能要放到不同的类中去,体现“单一职责原则”,便于维护,而去代码也不会复杂。单一职责原则,是优化代码的第一步