javasingleton-methods

How to extend a singleton class to handle a specific number of objects


In Java, I have created a singleton class as follows:

public class Singleton 
{   
    private Singleton() { print("Singleton Constructor"); }
    private static Singleton pointer = new Singleton();//static here so only one object 
    public static Singleton makeSingleton()
    {
        return pointer;
    }

    public static void main (String args[]) 
    {
        Singleton nuReference = Singleton.makeSingleton();
        if(nuReference == pointer)
        {
            print("Both are references for same object.");
        }
    }
}

Here, only the reference to an already-created object of Singleton class is being returned. How can I create a class so that only, say, four objects of that class are allowed to be created? Can I use this Singleton class for that or do I have to make it from scratch?

Oh, and print() is my custom method here. Works the same as System.out.println(), just with fewer keystrokes :)


Solution

  • That should work:

    public class Singleton
    {
          private Singleton()
          {
                print("Constructor");
          }
    
          private static Singleton instances[] = new Singleton[4];
    
          private static Boolean initiated = false;
    
          public static Singleton getInstance(int index)
          {
              tryInitiate();
    
              if(instances[index] == null)
              {
                  instances[index] = new Singleton();
              }
    
              return instances[index];
          }
    
          private static Boolean tryInitiate()
          {
              if(initiated) return false;
    
              for (int i = 0; i < instances.length; i++)
              {
                  instances[i] == null;
              }
    
              initiated = true;
    
              return true;
          }
    }
    

    Instead of initiating the objects with "null" you could also instantiate the objects during the initiation. But this way only the needed objects are instantiated.