简体   繁体   English

单例模式:多例?

[英]Singleton Pattern: Multiton?

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...

}

Multiton Design Pattern Multiton设计模式

The Multiton design pattern is an extension of the singleton pattern. Multiton设计模式是单例模式的扩展。 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/ http://www.ritambhara.in/multiton-design-pattern/

Another way using Singleton pattern is: 使用Singleton模式的另一种方法是:

To limit for 4 限制为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;
}


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM