一种模式是有其代表测试的结果对象,并代表执行块对象。结果对象重载了选择函数,所以如果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