public class OptimizingImagLoader {
ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
//单一职责,缓存功能只做缓存的工作
OptimizingImageCache mImageCache = new OptimizingImageCache();
public void displayImage(final String url, final ImageView imageView) {
imageView.setTag(url);
mExecutorService.submit(new Runnable() {
@Override
public void run() {
Bitmap bitmap = dowloadImage(url);
if (bitmap == null) {
return;
}
if (imageView.getTag().equals(url)) {
imageView.setImageBitmap(bitmap);
}
mImageCache.put(url, bitmap);
}
});
}
public Bitmap dowloadImage(String imageUrl) {
Bitmap bitmap = null;
try {
URL url = new URL(imageUrl);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
bitmap = BitmapFactory.decodeStream(connection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
迪米特原则-更好的扩展性
迪米特原则英文全称为Law of Demeter,缩写LOD 也成为最少知识原则(Least Knowledge Principle)即:一个对象应该对其他对象有最少的了解.通俗的讲--一个类应该对自己需要耦合或者调用的类知道得最少,类内部如何实现与调用或者依赖者关系,调用者或依赖者只需要知道它需要的方法即可,其他一概不管.
先看一下下面的demo
房子信息
public class Room {
public float area;
public float price;
public Room(float area, float price) {
this.area = area;
this.price = price;
}
@Override
public String toString() {
return "Room[area=" + area + ",price=" + price + "]";
}
}
中介
public class Mediator {
List mRooms = new ArrayList();
Mediator() {
for (int i = 0; i < 5; i++) {
mRooms.add(new Room(14 + i, (14 + i) * 150));
}
}
public List getAllRooms() {
return mRooms;
}
}
租户
public class Tenant {
public float roomArea;
public float roomPrice;
public static final float diffPrice = 100.0001f;
public static final float diffArea = 0.00001f;
public void rentRoom(Mediator mediator) {
List rooms = mediator.getAllRooms();
for (Room room : rooms) {
if (isSuitable(room))
System.out.println("租到房子了!" + room);
break;
}
}
private boolean isSuitable(Room room) {
return Math.abs(room.price) > diffPrice && Math.abs(room.area) > diffArea;
}
}
public class Mediator_Op {
List mRooms = new ArrayList();
public Mediator_Op() {
for (int i = 0; i < 5; i++) {
mRooms.add(new Room(14 + i, (14 + i) * 150));
}
}
//符合条件的房子输出给用户
public Room rentOut(float area, float price) {
for (Room room : mRooms) {
if (isSuitable(room, area, price)) {
return room;
}
}
return null;
}
//判断条件在中介内完成
private boolean isSuitable(Room room, float area, float price) {
return Math.abs(room.price - price) > Tenant.diffPrice && Math.abs(room.area - area) > Tenant.diffArea;
}
}
public class Tenant_op {
public float roomArea;
public float roomPrice;
public static final float diffPrice = 100.0001f;
public static final float diffArea = 0.00001f;
//只需要拿到结果
public void rentRoom(Mediator_Op mediator) {
System.out.println("租到房子了!" + mediator.rentOut(roomArea, roomPrice));
}
}