Softwaredesign: Beispiel: Iterator zum Implementieren von default-Methoden für Container |
interface Container {
boolean isEmpty();
int card();
int sum();
Object maximum();
Enumeration elements();
}
|
// analog zu java.util.Enumeration definiert
public
interface Enumeration {
public
boolean hasMoreElements();
public
Object nextElement();
}
|
abstract public class ContainerDefaults
implements Container {
public boolean isEmpty() {
return card() == 0;
}
public int card() {
int res = 0;
Enumeration i = elements();
while (i.hasMoreElements()) {
Object e = i.nextElement();
++res;
}
return res;
}
public int sum() {
int res = 0;
Enumeration i = elements();
while (i.hasMoreElements()) {
Object e = i.nextElement();
res += ((Integer)e).intValue();
}
return res;
}
public Object maximum() {
Comparable res = null;
Enumeration i = elements();
while (i.hasMoreElements()) {
Object e = i.nextElement();
if (res == null || res.compareTo(e) < 0)
res = (Comparable)e;
}
return res;
}
}
|
import java.util.NoSuchElementException;
public class Array
extends ContainerDefaults {
protected Object [] a;
public Array(Object [] a) {
this.a = a;
}
public Enumeration elements() {
return
new ArrayEnumeration(this);
}
// ----------------------------------------
static
private
class ArrayEnumeration implements Enumeration {
Array arr;
int i = 0;
public ArrayEnumeration(Array arr) {
this.arr = arr;
}
public boolean hasMoreElements() {
return i < arr.a.length;
}
public Object nextElement() {
if (! hasMoreElements())
throw new NoSuchElementException();
return arr.a[i++];
}
} // end ArrayEnumeration
}
|
import java.util.NoSuchElementException;
public class Array2
extends ContainerDefaults {
protected Object [] a;
public Array2(Object [] a) {
this.a = a;
}
public Enumeration elements() {
return
new ArrayEnumeration();
}
public Enumeration reverseElements() {
return
new ReverseArrayEnumeration();
}
// ----------------------------------------
// note: nested class to access field a in Array2
private
class ArrayEnumeration implements Enumeration {
int i = 0;
public boolean hasMoreElements() {
return i < a.length;
}
public Object nextElement() {
if (! hasMoreElements())
throw new NoSuchElementException();
return a[i++];
}
}
// ----------------------------------------
private
class ReverseArrayEnumeration implements Enumeration {
int i = a.length;
public boolean hasMoreElements() {
return i > 0;
}
public Object nextElement() {
if (! hasMoreElements())
throw new NoSuchElementException();
return a[--i];
}
}
}
|
|
Letzte Änderung: 13.04.2012 | © Prof. Dr. Uwe Schmidt |