我正在将我的游戏移至其自己的包中,以使其在未来的游戏中发挥作用。 我按照其中一位用户的建议实现了 Builders 类:Interfaces, static classes problem
public final class Builders {
public static Builder<? extends Sprite> newGameObjectBuilder(Point location, int drawable) {
return new GameObjectImpl.GameObjectBuilder(location, drawable);
}
}
现在的问题是客户端代码无法使用构建器方法(下面的示例)。我得到以下信息:
"The method onReceiveKey(new Sprite.ReceiveKeys(){}) is undefined for the type Builder<capture#4-of ? extends Sprite>"
基本上我无法使用公共(public)静态调用 GameObjectBuilder 中的任何方法。
onReceiveKey
不起作用。仅 Builder
接口(interface)的 build()
方法可用。
public static Sprite newSoldier(int x, int y) {
return Builders.newGameObjectBuilder(new Point(x,y), R.drawable.soldier)
.onReceiveKey(new Sprite.ReceiveKeys() {
@Override
public void onKeyUp(int keyCode, Sprite self, Room room ) {
}
@Override
public void onKeyDown(int keyCode, Sprite self, Room room ) {
if(keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
self.moveY(room, 1, Direction.S);
}
else if(keyCode == KeyEvent.KEYCODE_DPAD_UP){
self.moveY(room, -1, Direction.N);
}
else if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
self.moveX(room, -1,Direction.W);
}
else if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT){
self.moveX(room, 1, Direction.E);
}
}
})
.build();
}
最佳答案
问题是你的构建器是这样的
public interface Builder<T> {
public T build();
}
就这么做
public interface SpriteBuilder<T extends Sprite> extends Builder<T> {
Builder<T> onReceiveKey(Sprite.ReceiveKeys receiver);
}
并将构建器更改为
public final class Builders {
public static SpriteBuilder newGameObjectBuilder(Point location, int drawable) {
return new GameObjectImpl.GameObjectBuilder(location, drawable);
}
}
和你的GameObjectBuilder
到
class GameObjectImpl extends AbstractSprite {
public static class GameObjectBuilder implements SpriteBuilder {
...
}
}
关于java - 向客户端代码公开构建器类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2378132/