0

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

Shashi
  • 746
  • 10
  • 39
  • 2
    How are those 4 instances related? – Rohit Jain Aug 05 '13 at 15:56
  • 2
    If you need four of them, then it is not a singleton any more and you should just make it a normal class, possibly with caching if that makes sense... – assylias Aug 05 '13 at 16:01
  • Singletons should never have more than a single instance. That is the definition of a singleton. – Deactivator2 Aug 05 '13 at 16:01
  • the singleton is wrong. the makeSingleton() function should create the instance if needed. the way you wrote it, you might as well make every member of the class static. – x4rf41 Aug 05 '13 at 16:02
  • they need not to be related except being objects of same class. and say after 4 instances programmer tries to create an object, he gets a null reference or an error message or something like that – Shashi Aug 05 '13 at 16:02
  • Singleton is just for example here. my question is that can i use this Singleton class to create that class ? – Shashi Aug 05 '13 at 16:04
  • 1
    @Shashi: Why not just *create* 4 instances of a regular class, and stop there? I've heard there are only three numbers worth dealing with: 0, 1, and ∞. If you start designing the class itself to have "no more than 4" instances, you're doing something wrong -- and it's all but assured that in the future you will eventually need a 5th, but be unable to create it without redesigning stuff. – cHao Aug 05 '13 at 16:05

8 Answers8

3

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.

  • i understand everything except in tryInitiate method, why 'return true' their is no variable to hold the returned value. and also is 'return false' is just to end call to function or is their any other significance of this expressions being in starting of the method ? – Shashi Aug 05 '13 at 16:30
  • You're right. It's not really necessary. You could use return; instead of return false;. – Rafael Bankosegger Aug 05 '13 at 22:11
1

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~

charles_ma
  • 786
  • 7
  • 10
1

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;
}
}
Deactivator2
  • 311
  • 1
  • 10
0

create a variable x

increase its value every time when makeSingleton is called

if x<4 then return pointer

else return null

sandiee
  • 153
  • 1
  • 8
0

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.

ihsan kocak
  • 1,541
  • 1
  • 17
  • 26
0

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
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
0

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.

EZLearner
  • 1,614
  • 16
  • 25
0

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;
    }   
    
}
Priyak Dey
  • 1,227
  • 8
  • 20