Kev*_*ith 5 java effective-java
阅读Effective Java,我从Item 16: Favor composition over inheritance.
在下面InstrumentedSet,这本书显示我们可以跟踪元素被插入的次数(通过InstrumentedSet.addCount变量)。
要做到这一点,我们可以简单地附加到这个类对象的addCount,然后调用ForwardingSet.add(),它调用实际Set类的 实际实现add()。
// 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);
}
...
}
Run Code Online (Sandbox Code Playgroud)
我的理解是否正确,要使用这种模式/方法,Forwarding*类必须调用其所有父类的方法(在这种情况下Set)?
是的,您是对的,ForwardingSet将所有调用委托/转发到支持集。
您可能想看看流行的 Guava 库中的工作示例:ForwardingMap。
| 归档时间: |
|
| 查看次数: |
4505 次 |
| 最近记录: |