浅析面对对象 六大原则(二)

1.单一职责原则点击跳转

2.开闭原则(让程序更稳定、更灵活)

开闭原则的英文名是Open Close Principle,缩写是OCP ,他是JAVA世界里最基础的设计原则,他指导我们建立一个更稳定更灵活的系统。定义:软件中的对象(类,模块,函数等)应该对于扩展是开放的,但是对于修改是关闭的。在软件的升级、维护等需要在对其进行代码修改时,可能会将错误引入到原有系统,因此在需求发生变化时,我们应该尽量用扩展的方式来实现变化,而不是对原有的代码直接进行修改。当然了,直接通过继承的方式来实现是理想中的状态,往往在实现的过程中,代码修改和扩展代码是同时存在的。
在开发过程中,没有一成不变的需求,往往都会随着版本的迭代而进行修改,为了避免在其中可能由于引入新代码而导致的错误,请尽量遵守开闭原则。
继续就此系列博文,引用上篇博文的ImageLoader例子,添加允许用户可以设置缓存方式,那么上篇中的案例要添加相关的sdk存储相关的类,同时还要去大幅的修改ImageLoader类中的内容,并且用户在使用的同时,还要去处理相应的设置方式,这样需要改动的地方就会很多,违背了开闭原则。那么,我们应该怎么处理呢,最好的方式是通过引用一个接口,此接口主要定义了缓存的存与取方法,然后,多种缓存方式实现接口,在ImageLoader中直接调用接口,不管你是怎么实现的。UML类图如下

这里写图片描述

ImageCache接口代码如下:

public interface ImageCache {

    //设置Bitmap进缓存
    void putBitmap(String key , Bitmap bitmap);

    //从缓存中去Bitmap
    Bitmap getBitmap(String key);
}

修改过后的MemoryCache、DiskCache、DoubleCache如下:

public class MemoryCache implements ImageCache {
    //图片URL的缓存
    private LruCache<String, Bitmap> mImageCache;

    public MemoryCache() {
        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;
            }
        };
    }

    //从缓存中获取Bitmap
    @Override
    public Bitmap getBitmap(String key){
        return mImageCache.get(key);
    }

    //将加载出来的Bitmap存入缓存
    @Override
    public void putBitmap(String key , Bitmap bitmap){
        mImageCache.put(key,bitmap);
    }

}



public class DiskCache implements ImageCache {

    public static String cacheDir = "sdcard/cache/";

    @Override
    public void putBitmap(String key, Bitmap bitmap) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(cacheDir + key);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public Bitmap getBitmap(String key) {
        return BitmapFactory.decodeFile(cacheDir + key);
    }
}



public class DoubleCache implements ImageCache {

    private MemoryCache memoryCache = new MemoryCache();
    private DiskCache diskCache = new DiskCache();

    @Override
    public void putBitmap(String key, Bitmap bitmap){
        memoryCache.putBitmap(key, bitmap);
        diskCache.putBitmap(key, bitmap);
    }

    @Override
    public Bitmap getBitmap(String key) {
        Bitmap bitmap = memoryCache.getBitmap(key);
        if (bitmap == null){
            bitmap = diskCache.getBitmap(key);
        }
        return bitmap;
    }
}

ImageLoader代码如下:

public class ImageLoader {

    //图片缓存,默认为内存缓存
    ImageCache mImageCache = new MemoryCache();

    //线程池,线程数量为CPU的数量
    ExecutorService mExecutorService = Executors
            .newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //设置图片缓存方式
    public void setmImageCache(ImageCache mImageCache) {
        this.mImageCache = mImageCache;
    }

    //加载图片,并设置到对应的ImageView上
    public void displayImage(final String url, final ImageView imageView) {
        //直接调用ImgaeCache接口中的方法就OK
        Bitmap bitmap = mImageCache.getBitmap(url);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
            return;
        }
        imageView.setTag(url);
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                Bitmap bm = downloadBitmap(url);
                if (bm == null) {
                    Log.e("Chay", "请求出现未知问题。");
                    return;
                }
                if (imageView.getTag().equals(url)) {
                    imageView.setImageBitmap(bm);
                    //直接调用ImgaeCache接口中的方法就OK
                    mImageCache.putBitmap(url, bm);
                }
            }
        });
    }

    //加载图片
    private Bitmap downloadBitmap(String url) {
        Bitmap bitmap = null;
        try {
            URL uUrl = new URL(url);
            final HttpURLConnection coon = (HttpURLConnection) uUrl.openConnection();
            bitmap = BitmapFactory.decodeStream(coon.getInputStream());
            coon.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

}

可以看到,在ImageLoader中直接调用ImageCache接口,默认为MemoryCache,通过setImageCache(ImageCache)方法可以定义自己需要的缓存方式,或者是自定义的缓存方式,而在ImageLoader中的相关ImageCache代码也是使用接口定义的方法,以后在对ImageCache进行扩展时,只需要添加相应的类就可以了,不需要修改ImageLoader类,用户需要那种ImageCache缓存方式,直接设置即可。。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值