面向对象之接口隔离原则

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/feibendexiaoma/article/details/74857420

转载请注明出处:http://blog.csdn.net/feibendexiaoma/article/details/74857420
一.简称

英文全称InterfaceSegregation Principles,缩写是ISP。

二.定义

一种定义是:客户端不应该依赖于它不需要的接口;另一种定义是类间的依赖关系应该建立在最小的接口上。

三.问题

比如当我们用到流的时候,在最后都要做关闭操作,我们既要判断非空操作,又要try…catch,写一串代码,如果只用到一个类还好,要是类多的话,就要写很多了,是可忍孰不可忍。

四.解决

既然都要实现了Closeable接口,那么只要建立一个统一的方法来关闭这些对象就行了
举例

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

try…catch中有多层级的大括号,很容易将代码写到错误的层级中,如果有很多类都需要关流操作,那么每个类都要写这么多代码,想必也是挺烦人的,怎么解决呢?既然要实现Closeable接口,那就可以创建一个方法统一来关流。

public final class CloseUtil{
            private CloseUtil(){}
     public static void closeQuietly(Closeable closeable){
        if(null!=closeable){
            try{
                closeable.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

把关流的方法应用到put方法中:

public void put (String url,Bitmap bitmap){
        FileOutputStream fileOutputStream =null;
        try {
            fileOutputStream =new FileOutputStream(cacheDir + url);
            bitmap.compress(Bitmap.CompressFormat.PNG,100,fileOutputStream);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
           CloseUtil.closeQuitely(fileOutputStream);
        }
    }

代码瞬间清晰了好多,依赖于Closeable抽象而不是具体实现,并且建立在最小化依赖原则的基础上,只需要知道这个对象是可关闭的,其他的不需要担心,即接口隔离原则。

Bob大叔(Robert C Martin)在21世纪早期将单一职责、开闭原则、里氏替换原则、接口隔离以及依赖倒置5个原则定义为SOLID原则,作为面向对象编程的5个基本原则,当这些原则被一起应用时,它们使得一个软件系统更清晰、简单、最大程度地拥抱变化。

总结:

接口隔离优点:
(1)简洁代码
(2)接口最小化
(3)增加灵活性

猜你喜欢

转载自blog.csdn.net/feibendexiaoma/article/details/74857420
今日推荐