Which design pattern is appropriate for countable objects?

安稳与你 提交于 2019-12-25 03:23:03

问题


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.


回答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 SeaObjects 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!