如何正確實(shí)現(xiàn)java單例類

小樊
82
2024-09-09 10:44:28
欄目: 編程語言

在Java中,要正確地實(shí)現(xiàn)一個(gè)單例類,可以使用以下幾種方法:

  1. 懶漢式(Lazy Initialization):
public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
  1. 餓漢式(Eager Initialization):
public class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}
  1. 雙重檢查鎖定(Double-Checked Locking):
public class Singleton {
    private static volatile Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
  1. 靜態(tài)內(nèi)部類(Static Inner Class):
public class Singleton {
    private Singleton() {}

    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
  1. 枚舉(Enum):
public enum Singleton {
    INSTANCE;

    public void doSomething() {
        // ...
    }
}

以上五種方法都可以實(shí)現(xiàn)Java單例類。在實(shí)際項(xiàng)目中,可以根據(jù)需求和場(chǎng)景選擇合適的實(shí)現(xiàn)方式。

0