Can Singleton Pattern work on more than one (but fixed) number of instances

I came across a question about design patterns.

He asked the apt template template to be used in a script where exactly two instances of the class had ever been created. I was not sure of the answer, but later described that Singleton can be used for such a scenario. He said that Singleton can guarantee that either only one instance of a class is created, or a fixed number (except one).

I always read the Singleton template as a template in which you can only create one class object, and thus the explanation surprised me. I am not sure I agree with this.

Any thoughts?

Aditya

+4
source share
3

, Multiton, n :

public class Multiton
{
  private static Multiton[] instances;

  private Multiton() {}

  public static void initializeWithNumberOfInstances(int number)
  {
    instances = new Multiton[number];
  }

  public static Multiton getInstanceAtIndex(int index) throws Exception
  {
    if (instances == null)
      throw new Exception("Initialize number of instances first");

    if (instances[index] == null)
    {
      instances[index] = new Multiton();
    }

    return instances[index];
  }
}
+2

Singleton . Singleton :

1. ,
2.
3. , singleton.

, , . , .

class Singleton
{
     private static Singleton instance1 = null;
     private static Singleton instance2 = null;
     private Singleton{}
     public static Singleton getInstance()
     {

         if(instance1 == null)
         {
               instance1 = new Singleton();
               return instance1;
         }
         else if(instance2 == null)
         {
               instance2 = new Singleton();
               return instance2;
         }
         return instance1;
     }
}

, getInsatance, .

0

multiton (, , ), / producer-consumer, . " " , , , Dictionary HashMap, .

@Stefano GOF singleton static s , IoC .

0

All Articles