Softwaredesign: Beispiel: Funktionen |
interface Function {
int at(int x);
}
|
public
class Factorial implements Function {
public
int at(int x) {
int res = 1;
while ( x > 0 ) {
res *= x;
--x;
}
return
res;
}
}
|
public
class FunctionCache implements Function {
protected
Function f;
protected
Map values;
public
FunctionCache(Function f) {
this.f = f;
values = new Map();
}
public
int at(int x) {
if ( values.isIn(x) ) {
return
values.at(x); // use cached result
} else {
int y = f.at(x); // compute result
values.insert(x,y); // insert result into cache
return y;
}
}
}
|
class Test {
void foo() {
// cached version of factorial
Function fac =
new FunctionCache(new Factorial());
fac.at(42);
fac.at(42);
fac.at(43);
}
}
|
public
class Fibonacci implements Function {
public
int at(int x) {
return
(x <= 1) ? x : at(x-1) + at(x-2);
}
}
|
class Test2 {
void foo() {
Function fib =
new FunctionCache(new Fibonacci());
fib.at(42);
fib.at(41);
fib.at(43);
}
}
|
public
class FibonacciCache implements Function {
Function cache;
public FibonacciCache() {
cache = new FunctionCache(this);
}
public
int at(int x) {
return
(x <= 1) ? x : cache.at(x-1) + cache.at(x-2);
}
}
|
class Test3 {
void foo() {
Function fib =
new FibonacciCache();
fib.at(42);
fib.at(41);
fib.at(43);
}
}
|
public
class FibonacciCache2 implements Function {
Function cache;
public FibonacciCache2() {
cache = new FunctionCache(new Fibo());
}
public
int at(int x) {
return
cache.at(x);
}
private
class Fibo implements Function {
public
int at(int x) {
return
(x <= 1) ? x : cache.at(x-1) + cache.at(x-2);
}
}
}
|
Letzte Änderung: 13.04.2012 | © Prof. Dr. Uwe Schmidt |