一,优化代码的第一步—单一原则
单一原则是面向对象最简单的设计原则,它的主要目的是为了控制一个类的粒度大小。一个类只负责一个功能领域的职责,只封装相关性很高的函数、数据。根据具体的业务、功能对类进行相应的拆分。
需求:实现图片加载并且将图片缓存起来。
优化前
/**
* 图片加载类(优化前)
*/
public class ImageLoader {
//图片缓存(缓存到内存空间,应用重启会丢失)
LruCache<String, Bitmap> mImageCache;
//线程池
ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
public ImageLoader() {
initImageCache();
}
/**
* 初始化缓存
*/
private void initImageCache() {
//计算可使用的最大内存
final int maxMemory = (int) Runtime.getRuntime().maxMemory() / 1024;
final int cacheSize = maxMemory / 4;//取4/1的可用内存作为缓存
mImageCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String url, Bitmap bitmap) {
return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
}
};
}
public void displayImage(String url, ImageView imageView){
imageView.setTag(url);
mExecutor.submit(()->{
Bitmap bitmap=downLoadImage(url);
if(bitmap==null){
return;
}
if(imageView.getTag().equals(url)){
imageView.setImageBitmap(bitmap);
}
mImageCache.put(url,bitmap);
});
}
//把url加载到bitmap中
private Bitmap downLoadImage(String imageUrl) {
Bitmap bitmap=null;
try {
URL url=new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BitmapFactory.decodeStream(conn.getInputStream());
conn.disconnect();
} catch (Exception e) {
Log.i("TAG",e.getMessage());
}
return bitmap;
}
}
优化后:将图片加载,和缓存功能分开 如下图
/**
* 图片加载类(优化后)
*/
public class ImageLoader {
ImageCache mImageCache=new ImageCache();
//线程池
ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
public void displayImage(String url, ImageView imageView){
imageView.setTag(url);
mExecutor.submit(()->{
Bitmap bitmap=downLoadImage(url);
if(bitmap==null){
return;
}
if(imageView.getTag().equals(url)){
imageView.setImageBitmap(bitmap);
}
mImageCache.put(url,bitmap);
});
}
//把url加载到bitmap中
private Bitmap downLoadImage(String imageUrl) {
Bitmap bitmap=null;
try {
URL url=new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BitmapFactory.decodeStream(conn.getInputStream());
conn.disconnect();
} catch (Exception e) {
Log.i("TAG",e.getMessage());
}
return bitmap;
}
}
/**
* 图片缓存
*/
public class ImageCache {
//图片缓存(缓存到内存空间,应用重启会丢失)
LruCache<String, Bitmap> mImageCache;
public ImageCache() {
initImageCache();
}
/**
* 初始化缓存
*/
private void initImageCache() {
//计算可使用的最大内存
final int maxMemory = (int) Runtime.getRuntime().maxMemory() / 1024;
final int cacheSize = maxMemory / 4;//取4/1的可用内存作为缓存
mImageCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String url, Bitmap bitmap) {
return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
}
};
}
public void put(String url, Bitmap bitmap) {
mImageCache.put(url, bitmap);
}
public Bitmap get(String url) {
return mImageCache.get(url);
}
}
从上述的例子来看,我们能感受到单一职责的原则。根据具体的业务功能对类进行详细的划分。