Java – Ways to ensure unique instances of a class

javaobject-oriented

I'm looking for different ways to ensure that each instance of a given class is a uniquely identifiable instance.

For example, I have a Name class with the field name. Once I have a Name object with name initialised to John Smith I don't want to be able to instantiate a different Name object also with the name as John Smith, or if instantiation does take place I want a reference to the orginal object to be passed back rather than a new object.

I'm aware that one way of doing this is to have a static factory that holds a Map of all the current Name objects and the factory checks that an object with John Smith as the name doesn't already exist before passing back a reference to a Name object.

Another way I could think of off the top of my head is having a static Map in the Name class and when the constructor is called throwing an exception if the value passed in for name is already in use in another object, however I'm aware throwing exceptions in a constructor is generally a bad idea.

Are there other ways of achieving this?

Best Answer

Actually you have already answered your question. Your first way should be more effective here. Using static factory is always preferable than constructor wherever you think you can. So, you can avoid using Constructor in this case, else you would have throw some exception if an instance already exists with the given name.

So, you can create a static factory method: - getInstanceWithName(name) which will get the already available instance with that name, and if it does not exist, it will create a new instance, and make your constructor private, as it should mostly be done when dealing with static factories.

Also, for that you need to maintain a static List or Map of all the unique instances created, in your Factory class.

EDIT: -

You should certainly go through - Effective Java - Item#1 : Consider Static factories over Constructors. You can't get better explanation than that book.

Related Topic