> 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/12-lazy-singleton-aka-optimistic-lock-singleton.md).

# 1.2 Lazy Singleton (a.k.a Optimistic Lock Singleton)

定義: Lazy Singleton, 有時又稱為**樂觀鎖(optimistic lock)**&#x55AE;例, 即需要用到時才去檢查是否有實例, 通常此種做法是在第一次存取單例的時候會比較久, 因為第一次存取的時候尚未有任何實例, 所以要先進行初始化, 以下直接以程式說明.

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

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

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

    /*
     * Define a variable for saving instance that will be build.
     */
    private static Singleton uniqueInstance = null;

    /*
     * 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.
     * To ensure thread-safe, please add keyword synchronized in the method declaration.
     *
     * @return Singleton singleton instance
     */
    public static synchronized Singleton getInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }

    public void singletonOperation() {
        System.out.println("Do something here...");
    }

}
```

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