Help us understand the problem. What is going on with this article?

Singletonパターン

More than 3 years have passed since last update.

普通:

public class Singleton1 {
    public final static Singleton1 INSTANCE = new Singleton1 ();
    private Singleton1 () { }

}

進化バージョン:リフレクションでインスタンス作成防止

public class Singleton2 {
    private static boolean INSTANCE_CREATED;
    public final static Singleton2 INSTANCE = new Singleton2 ();
    private Singleton2 () {
        if (INSTANCE_CREATED) {
            throw new IllegalStateException("Singletonパターン です");
        } else {
            INSTANCE_CREATED = true;
        }
    }

Static Factoryバージョン:static factory

public class Singleton3 {
    public final static Singleton3 INSTANCE = new Singleton3 ();
    private Singleton3 () { }
    public static Singleton3 getInstance() { return INSTANCE; }

}

Lazy Initialization(遅延初期化):

public class Singleton4 {
    private Singleton4() {
    }
    public static Singleton4 getInstance() {
        return Singleton4Holder.INSTANCE;
    }
    private static class Singleton4Holder{
        private static final Singleton4 INSTANCE = new Singleton4 ();
    }
}

Enum使用

public enum EnumSingleton {
    INSTANCE;
    public static EnumSingleton getInstance() { return INSTANCE; }

}

EnumはSingletonに一番いいです。
理由は下記となっています。
1、クーロンできない
2、シリアライズしても、データコピー取得でいない
3、リフレクションもできない
https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9
Effective javaに記載があります

gaco777
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away