views:

53

answers:

1

I have a large number of objects which are identified by names (strings). So, I would like to have a kind of mapping from object name to the class instances.

I was told that in this situation I can use a "repository" class which works like that:

Server myServer = ServerRepository.getServer("NameOfServer");

So, if there is already an object (server) with the "NameOfServer" it will be returned by the "getServer". If such an object does not exist yet, it will be created and returned by the "getServer".

So, my question is how to program such a "repository" class? In this class I have to be able to check if there is an instance of a given class such that it has a given value of a given field. How can I do it? I need to have a kind of loop over all existing object of a given class?

Another part of my question is why I cannot use associative arrays (associative container, map, mapping, dictionary, finite map)? (I am not sure how do you call it in Java) In more details, I have an "array" which maps names of objects to objects. So, whenever I create a new object, I add a new element to the array: myArray["NameOfServer"] = new Server("NameOfServer").

+3  A: 

I would implement it with an associative container myself, however it is better to hide implementation details behind an appropriate interface. That makes it easier to use for clients, and easier for you to change/finetune the implementation over time.

For example, you may start out with a simple HashMap and find out later that for some reason, a TreeMap would be better. Or you realize that over time, a lot of unused objects accumulate in the map, which are not referenced by anyone else anymore but can't be garbage collected because the map keeps a reference to them. So you may decide to switch to a WeakHashMap. If your implementation is hidden behind an interface, you can do these changes without affecting clients.

Péter Török