Hi guys
I have a problem.
Short version:
I have an inventory and don’t know if I should use the singleton pattern or a class with only static members
Long version:
I’m currently making a game with an inventory class where you can add items and take items. the inventory is unique and contain
-a dictionaly (with the items and their quantities)
-methods to take and put items in the inventory
-methods to check if we have specific items
I created my inventory class as a classic class, but I rapidly found myself transorming the methods into static methods and variable into static variable. and in the end I only have static field.
Afraid that it maight cause some problems I looked on the web if all statics class were bad, and found this response (for java but that sould not change anything):
“Static classes are OK, just don’t forget to add a private constructor. Ah, and mind multi-threading accesses.”
“Make sure it doesn’t have any state. This is, there’s no field in the class unless it’s declared static final”
For the first one I guess the private constructor is to prevent ourself to instanciate it by mistake. I don’t think we can make the constructor private in unity but it’s a small project so I will just be carefull
The second statement is more problematic: my dictionary will have many state as the inventory content change all the time. However I don’t understant why it might be a problem as long as I deal with the concurential access.
I have many states, so I’m wondering if I should rather use the singleton pattern. I have heard many thing about the singleton patter. First that it was a normal and usefull pattern, then that it was an awefull pattern to avoid at all cost, and finaly that it is a good pattern as long as it is used correcly. But I have no idea if a unity inventory would be a good case for the singleton partern.
So yes… I don’t know if I should do a full static class. I don’t know if I should use the singleton patern. I don’t know if I should use something else but these king of classes are current in a game project, so I’m sure I’m not the first one to hesitate between the 2.
Do you guys have advice?