Softwaredesign: Beispiel 1: Schablonenmethode |
abstract
public
class Array {
protected
int [] a;
//--------------------
// the abstract compare method
// the variable part of the sort algorithm
abstract
protected
int compare(int i, int j);
//--------------------
// 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 ( compare(a[j], a[j+1]) > 0 ) {
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
}
}
}
}
|
public
class AscendingSortedArray
extends Array {
protected
int compare(int i, int j) {
return
( i == j )
? 0
:
( i > j )
? +1
: -1;
}
}
|
public
class DescendingSortedArray
extends Array {
protected
int compare(int i, int j) {
return
( i == j )
? 0
:
( i < j )
? +1
: -1;
}
}
|
public
class DescendingSortedArray1
extends AscendingSortedArray {
protected
int compare(int i, int j) {
return
0 - super.compare(i,j);
}
}
|
Letzte Änderung: 13.04.2012 | © Prof. Dr. Uwe Schmidt |