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.