Creating Objects which are Singleton wrt to a class variable

Hi Experts,
i have a class say,
class Child extends Parent{
public static Hashtable allChilds ;
public Child ( String name)
  super ( name ) ;

here allChilds wil have all the children,


after each child is created that will be put in the allchilds,
i want childs with only unique names,
I mean the Child class should be singleton with respect to name, so if i try to instantiate a Child with a name which is already existing in the allChilds table, then newInstance of child should not be created .. the existing instance in the allChilds table's reference should be assigned to the new reference variable..

now the problem is i cannot use a factory method ( like getInstance(name) etc..) i want to do it only with the constructor as shown above. is it possible??

LVL 10
Who is Participating?
mnrzConnect With a Mentor Commented:
so in constructor you can check it:

if( ! allChild.containsKey((String)name)){
    allChild.put(name,new Child())
elfe69Connect With a Mentor Commented:
You should definitely use a factory method. You will not be able to do what you want with a constructor anyway. So use a static getInstance(String) method.
JaaxConnect With a Mentor Commented:
As elfe69 has said, it is not possible to implement using a public constructor. Making the constructor of the singleton defeats the purpose, as the mere invocation of the constructor creates another instance - forget abt restricting the instance using code within the constructor.

Also the method that returns the instance shoul be synchronized
Here is a sample implementation
public class Singleton {
    private Singleton() {
    private static HashMap cache = new HashMap();

    public synchronized Singleton getSingleton(String key) {
        Singleton inst;
        if (cache.containsKey(key)) {
            inst = (Singleton) cache.get(key);
        } else {
            inst = new Singleton();
            cache.put(key, inst);
        return inst;
keyurkarnikConnect With a Mentor Commented:
There is no way you can achieve that with the constructor as mentioned by elfe and jaax.

You can either use static methods for it, or you could write a Factory class which will do the same work for you.
mukundha_expertAuthor Commented:
I just wanted to make sure that there is no other way.
Also throwing an exception from the constructor prevents the Object being succesfully instantiated.. so i was in doubt if there might be a way to actually refer to someother instance in memory//

anyways thanks a lot,

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.