blue-sky
blue-sky

Reputation: 53816

How to maintain a list of object references

I need to maintain a list of object references so that every time the object is initialized its object reference is stored.

The design I'm considering for this is to create a static list which lives in a singleton object. Every time a new object is created the reference is passed to the singleton and the List is updated. When I need to get all references I just get the List from the singleton and iterate. Is this good design or is there a better method?

Upvotes: 0

Views: 448

Answers (2)

Amir Afghani
Amir Afghani

Reputation: 38531

This is a pretty common scenario. Consider using a Map to avoid traversing a List each time when you wish to look something up.

Upvotes: 1

vgru
vgru

Reputation: 51224

Make your class constructor a private one, and then expose a factory method to instantiate it. That way it will only be possible to instantiate your class through that method, allowing you to do whatever you want with it (add it to a list, or whatever) before returning the instance.

Upvotes: 4

Related Questions