代码之家  ›  专栏  ›  技术社区  ›  linuxNoob

有效的Java第16项(第2版)-转发类是否仅用于允许重用?

  •  1
  • linuxNoob  · 技术社区  · 6 年前

    Effective Java, Item-16 Favor composition over inheritance . 我看了看 Forwarding class

    我想知道有个朋友有什么意义 ForwardingSet 上课? InstrumentedSet 可以很好的实施 Set 并且有一个调用所有方法的私有实例。

    如果我们最终拥有更多的资源,是为了促进重用和防止冗余吗 仪表集 像将来的类,除了基本行为之外还需要做些什么?它只是未来的设计证明,还是有其他东西,我错过了呢?

    // Reusable forwarding class 
    public class ForwardingSet<E> implements Set<E> {     
      private final Set<E> s;     
      public ForwardingSet(Set<E> s) { this.s = s; }     
      public void clear()               { s.clear();            }    
      public boolean contains(Object o) { return s.contains(o); }
    ...
    }
    
    // Wrapper class - uses composition in place of inheritance   
    public class InstrumentedSet<E> extends ForwardingSet<E> {     
          private int addCount = 0;     
          public InstrumentedSet(Set<E> s) { super(s); } 
          @Override public boolean add(E e) {         
              addCount++;
              return super.add(e);
           }
           ...
        }
    
    2 回复  |  直到 6 年前
        1
  •  6
  •   Olivier Grégoire    6 年前

    对, ForwardingSet 是一个框架。

    如果你要写几个 Set 那是和其他人一起工作的吗 ,公共部分最好写一次,不要写几次。

    约书亚·布洛赫,在华盛顿 通用程序设计 decorator pattern .

    Guava ,作为名为 ForwardingSet .

    对。

    对。

    不,你没有遗漏任何东西。

        2
  •  4
  •   Andreas dfa    6 年前

    是为了促进重用和防止冗余? 对。
    对。
    我还缺什么吗? 不。

    “转发”通常被称为 代表团 ".
    请参见: What is the purpose of a delegation pattern?

    具有仅委托实现的Java类的一些示例: