views:

85

answers:

3

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?

+2  A: 

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();
    }

}
Michael Barker
This looks like it might do the trick, I will give it a go.
jax
A: 

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 :-).

Tom
The clients will be building their own Sprites so I will not give them any pre-configured sprites
jax
Where is there a pre-configured sprite in my example? You said the client needs to use a builder right? My point is that you provide them a builder that only returns a Sprite (meaning they have to adhere to the Sprite interface... and you can make your implementation package-private). Does that make sense?
Tom
ok, I missunderstood
jax
A: 

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

Polaris878