结构模式之装配模式2

2019-04-13 21:57发布

  使用装饰模式   package com.javaeye.kang.decorator;   /**   * 模式要点:将主模 接口注入 展模   * 面向接口   * 点:能 很好地 付主模 的切 (上位切   * 缺点:无法很好地 付服 的切 (下位切 ,服   * 适用 合: Convert ReadFromFile 提供服 ,将来又 ReadFromNet   * 明: 缺点基本和 向适配器模式相反,可根据 实际 情况 选择   */   // 主模 接口 interface IRead {       public abstract void read(); }   // 实现 了主模 接口的 (从文件 取字符串) class ReadFromFile implements IRead {       public void read() {             System. out .println( " 从文件 取字符串 " );       } }   // 实现 了主模 接口的 (从网 络读 取字符串) class ReadFromNet implements IRead {       public void read () {             System. out .println( " 从网 络读 取字符串 " );       } }   // 模式 , 将主模 接口注入 来(使用 spring // 展模 ,可以 任何 实现 IRead 接口的主模 块类 提供服 class Convert {       private IRead iRead ;       public Convert(IRead iRead) {             this . iRead = iRead;       }       public void convertToUpper() {             iRead .read();             System. out .println( " 转换 成大写字母 " );       } }   // 端,最 使用方 public class DecoratorTest {       public static void main(String[] args) {            // 这边 可以使用 new Convert(new ReadFromFile()) 来从文件 取字符串            // 也可以使用 new Convert(new ReadFromNet()) 来从网 络读 取字符串             Convert convert = new Convert( new ReadFromFile());             convert.convertToUpper();       } }   测试结果:   从文件读取字符串
转换成大写字母
      假如改成: Convert convert = new Convert( new ReadFromNet());   则测试结果:   从网络读取字符串
转换成大写字母