面向对象的六大原则之 —— 接口隔离原则

学习了何红辉、关爱民写的《Android设计模式》,对于面向对象的六大原则有进一步的理解,特此根据自己的理解记录总结一下

什么是接口隔离原则

接口隔离的目的就是将庞大的接口拆分成更小的或者说更具体的接口,使得系统的耦合度大大降低,从而容易重构、修改等
[java] view plain copy
  1. /** 
  2.     * 缓存到sd卡 
  3.     * @param url 图片的url 
  4.     * @param bitmap bitmap对象 
  5.     */  
  6.    public void put(String url ,Bitmap bitmap){  
  7.        FileOutputStream output = null;  
  8.        try {  
  9.            output = new FileOutputStream(cacheDir+url);  
  10.            bitmap.compress(Bitmap.CompressFormat.PNG,100,output);  
  11.        } catch (FileNotFoundException e) {  
  12.            e.printStackTrace();  
  13.        }finally {  
  14.            //无论是否有异常,都要关闭流  
  15.            try {  
  16.                if(output!=null){  
  17.                    output.close();  
  18.                }  
  19.            } catch (IOException e) {  
  20.                e.printStackTrace();  
  21.            }  
  22.        }  
  23.   
  24.    }  
这段代码的可读性我就不说了,各种try...catch,没办法,因为在操作完流之后,要关闭流,可是有没有发现,如果你在类中加入的可关闭对象过多的时候,你的关闭代码就写的到处都是,这明显让人很不爽,看看jdk1.6的API,所有流都实现了Closeable接口,代表着可关闭,既然是这样,我们就把Closeable封装一下:
[java] view plain copy
  1. import java.io.Closeable;  
  2. import java.io.IOException;  
  3.   
  4. /** 
  5.  * Created by Administrator on 2016/3/1. 
  6.  */  
  7. public class CloseableUtil {  
  8.     public static void close(Closeable closeable){  
  9.         try {  
  10.             if(closeable!=null){  
  11.                 closeable.close();  
  12.             }  
  13.         } catch (IOException e) {  
  14.             e.printStackTrace();  
  15.         }  
  16.     }  
  17. }  

修改代码:
[java] view plain copy
  1. /** 
  2.      * 缓存到sd卡 
  3.      * @param url 图片的url 
  4.      * @param bitmap bitmap对象 
  5.      */  
  6.     public void put(String url ,Bitmap bitmap){  
  7.         FileOutputStream output = null;  
  8.         try {  
  9.             output = new FileOutputStream(cacheDir+url);  
  10.             bitmap.compress(Bitmap.CompressFormat.PNG,100,output);  
  11.         } catch (FileNotFoundException e) {  
  12.             e.printStackTrace();  
  13.         }finally {  
  14.             CloseableUtil.close(output);  
  15.         }  
  16.     }  
发现嵌套的try去掉了,瞬间觉得舒服很多
为什么我们能这样做,因为在JDK1.6中,所有的流都实现依赖了Closeable接口,具体的实现都在实现了Closeable接口的子类中,所以,这也是依赖倒置原则,子类只需要做细节的事,其他都不关心,这其实就是接口隔离原则,在ImageLoader中的ImageCahce就是接口隔离的运用,我们将ImageCache抽象出来,ImageLoader只需要知道该图片是不是有缓存,没缓存我就去网上下载,不管缓存的具体实现,也就是具体的实现对ImageLoader是隐藏的,它看不到,这就是我们将ImageLoader这个类的作用拆分的更加细致化的结果,ImageLoader跟其他三个实现类都没有直接关系,也就降低了耦合度,自然灵活度就上升了。
单一原则、开闭原则、里氏替换原则、依赖倒置原则、接口隔离原则,其实是相辅相成的,他们同一时刻出现的时候,使得一个软件系统更新清晰、最大程度拥抱变化。
原文地址:https://www.cnblogs.com/zhaoshujie/p/9594664.html