Reputation:
I am confused as to how the multiton implementation of the singleton pattern works. I am aware that the definition of a singleton is as follows:
Ensure a class allows only one object to be created, providing a single point of access to it.
However, when using the enum version of the singleton pattern, would the multiton not allow for more than one object of the class to be created?
For example:
Public enum myFactory{
INSTANCE1, INSTANCE2;
//methods...
}
Upvotes: 2
Views: 5713
Reputation: 11
Another way using Singleton pattern is:
To limit for 4
package org.dixit.amit.immutable;
import java.util.Random;
public class ThreadSafeSingleton {
private ThreadSafeSingleton(){
}
private static ThreadSafeSingleton threadSafeSingleton[] = new ThreadSafeSingleton[3];
static int i = -1;
public static ThreadSafeSingleton getInstance(){
i++;
System.out.println("i is ---> "+i);
if(i<3 && threadSafeSingleton[i]==null){
synchronized (ThreadSafeSingleton.class) {
if(threadSafeSingleton[i]==null){
threadSafeSingleton[i] = new ThreadSafeSingleton();
return threadSafeSingleton[i];
}
}
}
int j = randInt(0, 4);
return threadSafeSingleton[j];
}
private static int randInt(int min, int max) {
// Usually this can be a field rather than a method variable
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
Upvotes: 1
Reputation: 2185
Multiton Design Pattern
The Multiton design pattern is an extension of the singleton pattern. It ensures that a limited number of instances of a class can exist by specifying a key for each instance and allowing only a single object to be created for each of those keys.
So Enum is best example
http://www.ritambhara.in/multiton-design-pattern/
Upvotes: 3