Question

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 :)

Was it helpful?

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.

OTHER TIPS

Add a static int count = numyouwant; to your code, every time the static creation method is called, reduce the count by 1. and more importantly, check whether count is 0 before call the private constructor in the creation method~

Singletons, by definition, only have a single instance of itself. What you're suggesting sounds like you would make better use of a Factory-type paradigm, along with a counter/limiter (built into the class).

Make a Factory class that contains a counter (or a list to store created objects, if you prefer) and a createObject method. In the method, do your logic for determining whether there are too many objects, and therefore you may limit creation of the objects.

Here's an example of a Factory with a max limit on created objects. The object in question is an inner class for simplicity.

public class Factory {
private final int maxObj = 4;

public class MyObject {
    MyObject() { print("Constructor"); }
}

private List<MyObject> objects = new List<Object>();

// Returns new MyObject if total MyObject 
// count is under maxObj, null otherwise
public MyObject makeObject() {
    if (objects.length() >= maxObj)
        return null;
    MyObject obj = new MyObject();
    objects.add(obj);
    return obj;
}
}

create a variable x

increase its value every time when makeSingleton is called

if x<4 then return pointer

else return null

Create a field of List<Singleton> mySingletons; and a field int singletonCounter=0;

in makeSingleton() method add 1 to counter if it is equal to 4 return null or return a singleton of 4.If counter is less than 4 then create a singleton.

my question is that how can i create a class so that say only 4 objects of that class are allowed to be created. any help ? can i use this Singleton class for that or do i have to make it from scratch ?

I believe you want to keep a pool of objects of a class . You can't do it through a Singleton class , which by definition should return the only instance it has.

Suggested reads:

  1. Object Pool in Java .
  2. Build your own ObjectPool

You could add a Queue of 4 instances of the same object, and manage the queue/dequeue operations.

Beware: Sounds you should apply thread-safety for those operations.

I created one with Thread Safty

import java.util.ArrayList;
import java.util.List;

public class SingletonLimit{
    
    private List<SingletonLimit> inst_Obj= new ArrayList<>();
    private static final int maxLimit=4;
    
    private SingletonLimit(){
    }
    
    public SingletonLimit getInstance(){
        if(inst_Obj.size()>=maxLimit)
                return null;
        SingletonLimit singleLimit=null;        
        synchronized(SingletonLimit.class){
            singleLimit= new SingletonLimit();
            inst_Obj.add(singleLimit);
        }
        return singleLimit;
    }   
    
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top