设计模式 一一一 装饰模式

适配器模式:
    目的:适配器暴露符合外界规范的接口,该接口的具体实现经过调用被适配对象的相应方法来完成。
    
    应用:系统须要使用现有的一个类,可是这个类的接口不符合系统的须要,此时就须要新增一个适配器来解决这个问题。this

    角色:
        目标接口:符合外界规范的接口
            
        源对象(被适配的对象):提供相应的功能,可是接口的规范不符合外界的要求
            
        适配器:暴露符合外界规范的接口,经过调用被适配对象的相应方法,而后对其结果进行必定加工来实现。
            
            
jdk中的适配器模式:
    /**
     * 目标接口:Reader。 
     *         说明:Reader的目标是读取数据,可是只能按照字符来读取。
     * 源对象(被适配的对象):InputStream的子类
     *         说明:InputStream能够读数据,可是只能按字节来读取
     * 适配器:InputStreamReader
     *         说明:InputStreamReader经过InputStream来读取数据,而且将读取到的字节流转换为字符流,而后提供给Reader进行读取。
     */        
    public class InputStreamReader extends Reader {code

        // StreamDecoder里面封装了InputStream对象,即InputStreamReader间接地封装了InputStream对象。
        private final StreamDecoder sd;对象

        /**
         * 将源对象(被适配的对象)传入进来,这里源对象能够是InputStream的任何一个子类。
         */
        public InputStreamReader(InputStream in) {
            super(in);
            try {
                sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // 将in封装到sd中。
            } catch (UnsupportedEncodingException e) {
                // The default encoding should always be available
                throw new Error(e);
            }
        }
        
        // 按照字符来读取数据
        public int read() throws IOException {
            return sd.read(); // 使用in来读取数据,而后将读取到的字节流转换为字符流后,再去读取。
        }
    }接口

相关文章
相关标签/搜索