# 1. Singleton

定義: 保證一個類別僅有一個實例, 並提供一個存取該類別實例的全局存取點

結構與說明:\
![](https://1264106928-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M523o3BFdjQwXhOl9_Z%2F-M523s31WfODDGzKviNo%2F-M523v69M27gmAgrGzU_%2Fsingleton_001.png?generation=1587042038792485\&alt=media)

Singleton: 負責創造Singleton類別自己的唯一實例, 並提供一個getInstance()方法, 讓外部來存取這個類別的唯一實例.

認識singleton pattern:

1. Singleton pattern的功能: 用來保證這個類別在runtime期間只會被創造一個類別實例, 並**提供一個全局唯一存取這個類別實例的存取點**.
2. Singleton pattern的範圍(即在什麼範圍下是單例): **是一個classloader及其子classloader的範圍**, 以eager singleton來說, 會在singleton類別被JVM加載的時候即初始化該類別的實例, 由於現在一般來說, 一個JVM只有一個classloader, 所以也可以說是在一個JVM的範圍內(比較不嚴謹的講法).
3. Singleton pattern的命名: 一般建議取得單例的方法命名為: **getInstance()**


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://clu.gitbook.io/design-pattern/chapter1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
