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 relati开发者_运维问答onship: 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
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.
精彩评论