Softwaredesign: Beispiel: Strategie |
public
class Array {
protected
int [] a;
//--------------------
// the reference to the compare object
// defining the compare method
protected
CompareFunction c;
//--------------------
public
Array(CompareFunction c) {
// a = ...
this.c = c;
}
//--------------------
// the template method
public
void sort() {
// simple bubble sort
// --> 2 nested loops
for (int i = a.length -1;
i >= 0;
--i ) {
for (int j = 0;
j < i;
++j ) {
if ( c.compare(a[j], a[j+1]) > 0 ) {
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
}
}
}
}
|
public
class AscendingCompare
implements CompareFunction {
public
int compare(int i, int j) {
return
( i == j )
? 0
:
( i > j )
? +1
: -1;
}
}
|
public
class DescendingCompare
implements CompareFunction {
public
int compare(int i, int j) {
return
( i == j )
? 0
:
( i < j )
? +1
: -1;
}
}
|
Letzte Änderung: 13.04.2012 | © Prof. Dr. Uwe Schmidt |