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?
I'm aware that one way of doing this is to have a static factory that holds a Map...
So why don't you want to do it this way?