问题
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:
I want to generalize objects with help of an abstract class or interface.
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.
回答1:
Check out object pool pattern. It's basically a factory which keeps count of the things it creates.
回答2:
You must have a reference to these objects somewhere or you cannot use them. In Java if you have no reference to an object it will just be garbage collected, in c++ it causes a memory leak.
I also see no value in a SeaObject
knowing how many other SeaObject
s there are so that it can limit it's own creation. Other code should make that decision.
So in your game class, you should have a list of the objects. That way it is easy to see how many there are currently and you will need it to interact with or draw these objects:
public class Game {
private static final int MINE_LIMIT = 10;
private final ArrayList<Mine> mines = new ArrayList<Mine>();
public void addNewMineIfNotTooManyAlready() {
if(mines.size() < MINE_LIMIT) {
mines.add(new Mine());
}
}
}
The list mines
could be a list of a super type like SeaObject
if you wish/require.
来源:https://stackoverflow.com/questions/25184089/which-design-pattern-is-appropriate-for-countable-objects