Softwaredesign: Beispiel: Strategie zum Implementieren von default-Methoden für Container |
interface Container {
boolean isEmpty();
int card();
int sum();
Object maximum();
Object processAll(Command c);
}
|
abstract public
class ContainerDefaults
implements Container {
public boolean isEmpty() {
return card() == 0;
}
public int card() {
Command c = new Command() {
// anonyme Klasse !
int res = 0;
public void process(Object e) {
++res;
}
public Object getResult() {
return new Integer(res);
}
};
return ((Integer)processAll(c)).intValue();
}
public int sum() {
Command c = new Command() {
// anonyme Klasse !
int res = 0;
public void process(Object e) {
res += ((Integer)e).intValue();
}
public Object getResult() {
return new Integer(res);
}
};
return ((Integer)processAll(c)).intValue();
}
public Object maximum() {
Command c = new Command() {
// anonyme Klasse !
Comparable res = null;
public void process(Object e) {
if (res == null || res.compareTo(e) < 0)
res = (Comparable)e;
}
public Object getResult() {
return res;
}
};
return processAll(c);
}
}
|
public class Array extends ContainerDefaults {
protected Object [] a;
public Array(Object [] a) {
this.a = a;
}
public Object processAll(Command c) {
for (int i = 0; i < a.length; ++i) {
c.process(a[i]);
}
return c.getResult();
}
}
|
|
Letzte Änderung: 13.04.2012 | © Prof. Dr. Uwe Schmidt |