一種模式是有其代表測試的結果對象,並代表執行塊對象。結果對象重載了選擇函數,所以如果Bool有一個選擇(T positive,T negative),則Bool.TRUE將返回正參數,Bool.FALSE將返回負值。天真的Smalltalk家族語言的實現就是這樣工作的。
要以這種形式對while循環進行編碼,需要對比較x和y的結果調用choose方法來確定是否調用while循環內部的塊,並且該塊還使用compare和選擇設置x的值。更直接的翻譯可能是選擇一個將x設置爲z的塊或者一個不執行任何操作的塊;相反,它只是使用選項將x設置回相同的值。
很明顯,這對於這個簡單的案例來說是過分的和低效的。
public class WantonPolymorphism {
static class Int32 {
final int value;
Int32 (final int value) { this.value = value; }
Compare compare (Int32 other) {
// Java runs out of turtles at this point unless you use
// an enum for every value
if (this.value < other.value) return Compare.LESS;
if (this.value > other.value) return Compare.GREATER;
return Compare.EQUAL;
}
}
enum Compare {
LESS {
<T> T choose (T less, T equal, T greater) { return less; }
},
EQUAL {
<T> T choose (T less, T equal, T greater) { return equal; }
},
GREATER {
<T> T choose (T less, T equal, T greater) { return greater; }
};
abstract <T> T choose (T less, T equal, T greater) ;
}
interface Block { Block execute() ; }
/**
* Main entry point for application.
* @param args The command line arguments.
*/
public static void main (String...args) {
Block block = new Block() {
Int32 x = new Int32(4);
Int32 y = new Int32(3);
Int32 z = new Int32(2);
public Block execute() {
System.out.printf("x = %d, y = %d, z = %d\n", x.value, y.value, z.value);
return x.compare(y).choose(done, done, new Block() {
public Block execute() {
x = x.compare(z).choose(x,x,z);
return x.compare(y).choose(done, done, this);
}
});
}
Block done = new Block() {
public Block execute() {
System.out.printf("x = %d, y = %d, z = %d\n", x.value, y.value, z.value);
System.exit(0);
return this;
}
};
};
for(;;)
block = block.execute();
}
}
@ken謝謝你接觸錯字。我做了很多。 – WolfmanDragon 2009-02-06 08:32:46