开发者

Interfaces, static classes problem

开发者 https://www.devze.com 2022-12-22 07:47 出处:网络
I am currently moving all my Game code to another package so that I can simply reuse it when I create another similar game.

I am currently moving all my Game code to another package so that I can simply reuse it when I create another similar game.

I am having some problems with this though.

public interface Sprite {
...
}

abstract class AbstractSprite implements Sprite {
...
}

public interface Builder<T> {
    public T build();
}

class GameObjectImpl extends AbstractSprite {
    public static class GameObjectBuilder implements Builder<GameObjectImpl> {
    ...
    }
}

I am using a Builder Pattern to create开发者_运维百科 my GameObjectImpl objects. However, the client (the person using my game engine) will only have access to the Sprite interface.

How can I get the client to create GameObjectImpl using builder and only having access to the Sprite Interface?


You could add one more publicly visible class in the same package called Builders:

public final class Builders {

    public static Builder<? extends Sprite> newGameObjectBuilder() {
        return new GameObjectImpl.GameObjectBuilder();
    }

}


Why does Builder need to be an interface? Why not just make a builder-like factory? It seems like you want to tie the interface to this particular implementation.

public final class SpriteBuilder {
  private final Foo foo;
  private int property = 0;

  public SpriteBuilder(Foo importantMandatoryValue) {
    this.foo = importantMandatoryValue;
  }

  public SpriteBuilder setProperty(int theProperty) {
    this.property = property;
    return this;
  }

  public Sprite build() {
    return new GameObjectImpl(foo, property);
  }
}

You might call SpriteBuilder a GameObjectImplFactory... and make a similar class for each one of your Sprite implementations. You just have to make sure they will only return the Sprite type.

In your example, you would actually say something like public class GameObjectImplFactory implements Builder<Sprite>.

Hope this helps and makes sense :-).


I don't think you would want to make the Builder class generic... instead Builder.build() should be returning a Sprite object. Right now the build() method is returning T which in your case is a GameObjectImpl

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号