一种模式是具有代表测试结果的对象和代表要执行的块的对象。结果对象具有覆盖的选择函数,因此如果 Bool 有一个 choose(T positive, Tnegative) 则 Bool.TRUE 将返回正参数,而 Bool.FALSE 将返回负数。 smalltalk 系列语言的幼稚实现就是这样工作的。
要以这种形式编码你的while循环,需要在比较x和y的结果上调用choose方法来确定是否调用while循环内部的块,并且该块也使用比较和选择设置 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();
}
}