inheritance is a powerful measure to realize code reuse,howere it maybe not the best tool to finish the demand.inheritance break the encapsulation of the class,we also can describe that subclass rely on its superclass's implement details by spacial function.
if we extends the supclass directly.we can know the method of the HashSet.we may ingnore the realize detail of it.

fortunately,we can add a private area in new class.instead of extending existing class,such the following code,we called it as forwarding. newclass's menthod called as forwarding method.it is steady on account of it do not rely on existing class's readlize detail.
package Other;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
/**
* @author 韦海涛
* @version 1.0
* @date 4/3/2021 10:00 PM
*/
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);
}
@Override
public boolean addAll(Collection<? extends E> c) {
addCount += c.size();
return super.addAll(c);
}
public int getAddCount() {
return addCount;
}
}
class ForwardingSet<E> implements Set<E>{
private final Set<E> s;
//add a construct method
public ForwardingSet(Set<E> s) {
this.s = s;
}
@Override
public int size() {
return s.size();
}
@Override
public boolean isEmpty() {
return s.isEmpty();
}
@Override
public boolean contains(Object o) {
return s.contains(o);
}
@Override
public Iterator<E> iterator() {
return iterator();
}
@Override
public Object[] toArray() {
return s.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return s.toArray(a);
}
@Override
public boolean add(E e) {
return s.add(e);
}
@Override
public boolean remove(Object o) {
return s.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return s.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
return s.addAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return s.retainAll(c);
}
@Override
public boolean removeAll(Collection<?> c) {
return s.removeAll(c);
}
@Override
public void clear() {
s.clear();
}
}
wrapped class hardly any disadvantage nearly,but we need pay attention that wrapped class is no suitable for callback framework,because in the callback framework.object transmit itself to other class,and use on following callback.the object which wrapped do not know the wrapped object outside,so it transmit a reference point this.so callback should avoid appear in callback framework.

本文探讨了继承作为代码复用的强大工具,但可能不是所有需求的最佳解决方案。它强调了继承如何打破封装,以及通过特殊方法暴露父类细节的问题。通过引入ForwardingSet概念,文章提倡在新类中创建私有区域,避免直接依赖父类实现,适用于回调框架。
1347

被折叠的 条评论
为什么被折叠?



