Search code examples
javadesign-patterns2d-games

Which design pattern is appropriate for countable objects?


I have a problem that I can't solve again. As junior developer that have recently got acquainted with design patterns and doesn't deal with them yet, I need your help to find appropriate.

The issue is:

  1. I want to generalize objects with help of an abstract class or interface.

  2. I want to count every instance of derived class, because I need to limit their number.

For example in "Sea Battle" game I use classes: SeaObject ----> Mine, Boat, Kreyser. The quantity of mines,boats,etc are limited

I have tried to use static field 'count' in base class and I don't understand how to use it in the right way in derived. Because all that I could just copy and paste the static fields again. I suspect that it is not good :[.

I agree that my decision to use abstract class SeaObject is not quite right. If the better choice exists I would use it.

Please, don't be strict to me, I am a newcomer here. Thank you for any help.


Solution

  • Check out object pool pattern. It's basically a factory which keeps count of the things it creates.