您的位置:首页 > 其它

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

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


什么是接口隔离原则

接口隔离的目的就是将庞大的接口拆分成更小的或者说更具体的接口,使得系统的耦合度大大降低,从而容易重构、修改等

在《面向对象的六大原则之
—— 单一原则》中我们有如下代码:

[java] view
plain copy

/** 

    * 缓存到sd卡 

    * @param url 图片的url 

    * @param bitmap bitmap对象 

    */  

   public void put(String url ,Bitmap bitmap){  

       FileOutputStream output = null;  

       try {  

           output = new FileOutputStream(cacheDir+url);  

           bitmap.compress(Bitmap.CompressFormat.PNG,100,output);  

       } catch (FileNotFoundException e) {  

           e.printStackTrace();  

       }finally {  

           //无论是否有异常,都要关闭流  

           try {  

               if(output!=null){  

                   output.close();  

               }  

           } catch (IOException e) {  

               e.printStackTrace();  

           }  

       }  

  

   }  

这段代码的可读性我就不说了,各种try...catch,没办法,因为在操作完流之后,要关闭流,可是有没有发现,如果你在类中加入的可关闭对象过多的时候,你的关闭代码就写的到处都是,这明显让人很不爽,看看jdk1.6的API,所有流都实现了Closeable接口,代表着可关闭,既然是这样,我们就把Closeable封装一下:

[java] view
plain copy

import java.io.Closeable;  

import java.io.IOException;  

  

/** 

 * Created by Administrator on 2016/3/1. 

 */  

public class CloseableUtil {  

    public static void close(Closeable closeable){  

        try {  

            if(closeable!=null){  

                closeable.close();  

            }  

        } catch (IOException e) {  

            e.printStackTrace();  

        }  

    }  

}  

修改代码:

[java] view
plain copy

/** 

     * 缓存到sd卡 

     * @param url 图片的url 

     * @param bitmap bitmap对象 

     */  

    public void put(String url ,Bitmap bitmap){  

        FileOutputStream output = null;  

        try {  

            output = new FileOutputStream(cacheDir+url);  

            bitmap.compress(Bitmap.CompressFormat.PNG,100,output);  

        } catch (FileNotFoundException e) {  

            e.printStackTrace();  

        }finally {  

            CloseableUtil.close(output);  

        }  

    }  

发现嵌套的try去掉了,瞬间觉得舒服很多

为什么我们能这样做,因为在JDK1.6中,所有的流都实现依赖了Closeable接口,具体的实现都在实现了Closeable接口的子类中,所以,这也是依赖倒置原则,子类只需要做细节的事,其他都不关心,这其实就是接口隔离原则,在ImageLoader中的ImageCahce就是接口隔离的运用,我们将ImageCache抽象出来,ImageLoader只需要知道该图片是不是有缓存,没缓存我就去网上下载,不管缓存的具体实现,也就是具体的实现对ImageLoader是隐藏的,它看不到,这就是我们将ImageLoader这个类的作用拆分的更加细致化的结果,ImageLoader跟其他三个实现类都没有直接关系,也就降低了耦合度,自然灵活度就上升了。

单一原则、开闭原则、里氏替换原则、依赖倒置原则、接口隔离原则,其实是相辅相成的,他们同一时刻出现的时候,使得一个软件系统更新清晰、最大程度拥抱变化。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: