> For the complete documentation index, see [llms.txt](https://clu.gitbook.io/design-pattern/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://clu.gitbook.io/design-pattern/11-eager-singleton-aka-pessimistic-lock-singleton.md).

# 1.1 Eager Singleton (a.k.a Pessimistic Lock Singleton)

定義: Eager Singleton, 有時又稱**悲觀鎖(pessimistic lock)**&#x55AE;例, 亦即在類別中把實例宣告為私有靜態的屬性, 以下直接以程式說明.

```java
package idv.design.pattern.singleton.eager;

/**
 * @author Carl Lu
 */
public class Singleton {

    /*
     * This is also called "pessimistic lock singleton".
     */

    /*
     * Define a variable for saving instance, new the instance here.
     * The JVM will guarantee that the class will be instantiated for only one time,
     * so this way is thread-safe.
     */
    private static final Singleton uniqueInstance = new Singleton();

    /*
     * The constructor should be private so that we can control the instance number.
     */
    private Singleton() {

    }

    /*
     * Need to define a method for providing class instance to clients.
     *
     * @return Singleton singleton instance.
     */
    public static Singleton getInstance() {
        return uniqueInstance;
    }

}
```

原始碼[點我](https://github.com/yotsuba1022/design-pattern/blob/master/src/main/java/idv/design/pattern/singleton/eager/Singleton.java)
