0

I'm trying to make a simple game. I have a class for the screen buffer, a class for the images, and a class for the sprites. My question is this:
Since every sprite needs to "belong" to some image (the sprite only holds the coordinates within some image, and a pointer/reference to an image), should I pass the image class to the sprite constructor, like so:

Sprite spriteInstance(imageInstance, rect, ...);

or have the sprites returned by a method of the image class

Sprite spriteInstance = imageInstance.createSprite(rect, ...);

or does it a matter of personal preference. (both obviously work, I'm just wondering if one is considered the "right" or "professional" way to do it.)
The same goes for the image/screen relationship: Should the surface be returned by the screen, or the image passed the screen.

A third option which I haven't tried to implement yet would be to have a "Game" class, and do this:

Game gameInstance;
Image imageInstance = gameInstance.loadImage(path);
Sprite spriteInstance = gameInstance.newSprite(imageInstance, rect, ...);

If the second/third methods above are recommended, should the sprite class constructor be made private with the image class as a "friend", or left as public? And does this type of method have a name that I can look up for further insight? Is this what is referred to as the "Factory pattern"?

Thanks

Baruch
  • 20,590
  • 28
  • 126
  • 201

1 Answers1

1

It seems like you've got two separate questions here: where to put the logic for creating a sprite based on an image, and whether to use a factory method or not.

I would advise against imageInstance.createSprite unless it actually makes sense for an Image to know that there exists some class named Sprite. You want to keep visibility uni-directional if at all possible. Therefore unless an image depends on the sprite, don't let it even know the class Sprite exists.

I might suggest

Sprite s = Sprite.forImage(image, rect);

I can't say much more without knowing more about the classes (and responsibilities of) Game, Image, and Sprite.

As for factory methods, yeah go nuts. Effective Java has a good chapter on their merits.

Mark Peters
  • 80,126
  • 17
  • 159
  • 190
  • At the moment I don't have a game class. Maybe I should. I mentioned it as a thought that occurred to me to have one object in charge of all aspects of the game, including creating the objects – Baruch Nov 17 '10 at 21:42
  • Yeah this is correct. The naming forImage is not too clear to me thought, maybe some verb ? If it was Create.Sprite.forImage it would be. Here Create is your static or singleton (aka the factory), Sprite is property object and forImage is method for the class of Sprite – user44298 Nov 17 '10 at 21:49