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

记得在操作IO流时,在最后要关闭流的时候要try/catch,流多的时候就有一大堆try/catch,如下所示:

private void put(String path, Bitmap bitmap) 
    {
        FileOutputStream fos = null;
        try 
        {
            fos = new FileOutputStream(path);
            bitmap.compress(CompressFormat.JPEG, 100, fos);
        } catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        }finally
        {
            if(fos != null)
            {
                try 
                {
                    fos.close();
                } catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
        }

今天看了面向对象的接口隔离原则,原来可以这样处理(虽然多了一个工具类,但代码明显看着顺眼多了:


        public final class CloseUtils
        {
            private CloseUtils()
            {

            }
            public void closeQuietly(Closeable closeable)
            {
                if(closeable != null)
                {
                    try 
                    {
                        closeable.close();
                    } catch (IOException e) 
                    {
                        e.printStackTrace();
                    }
                }
            }
        }

这个时候上面的put()方法就可以这样写了,代码是不是简洁顺眼多了呢,而且这个CloseUtils还可以应用到各类可关闭的对象中,保证了代码的重用性:

    private void put(String path, Bitmap bitmap) 
    {
        FileOutputStream fos = null;
        try 
        {
            fos = new FileOutputStream(path);
            bitmap.compress(CompressFormat.JPEG, 100, fos);
        } catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        }finally
        {
            if(fos != null)
            {
                CloseUtils.closeQuietly(fos);
            }
        }
    }

你可能感兴趣的:(Java)