Ways to ensure unique instances of a class?
Posted
by
Peanut
on Programmers
See other posts from Programmers
or by Peanut
Published on 2012-10-22T17:44:26Z
Indexed on
2012/10/22
23:17 UTC
Read the original article
Hit count: 444
java
|object-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?
© Programmers or respective owner