2

シングルトン パターンのマルチトン実装がどのように機能するかについて混乱しています。シングルトンの定義は次のとおりであることを認識しています。

クラスが作成できるオブジェクトは 1 つだけであることを確認し、オブジェクトへの単一のアクセス ポイントを提供します。

しかし、シングルトン パターンの enum バージョンを使用する場合、マルチトンではクラスの複数のオブジェクトを作成できないでしょうか?

例えば:

Public enum myFactory{

INSTANCE1, INSTANCE2;

//methods...

}
4

2 に答える 2

1

シングルトン パターンを使用する別の方法は次のとおりです。

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;
}


}
于 2014-08-23T20:21:21.630 に答える