> For the complete documentation index, see [llms.txt](https://wilden-chen.gitbook.io/swift-design-patterns/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wilden-chen.gitbook.io/swift-design-patterns/singleton.md).

# 單例模式 - Singleton

單例模式確保每個指定的類別只存在一個實例對象，並且可以全局訪問那個實例。一般情況下會使用延時加載的策略，只在第一次需要使用的時候初始化。

注意：在 iOS 中單例模式很常見，`UserDefaults.standard` 、 `UIApplication.shared` 、 `UIScreen.main` 、 `FileManager.default` 這些都是單例模式。

你可能會疑惑了：如果多於一個實例又會怎麼樣呢？程式碼和記憶體有貴重到這個程度嗎？

某些場景下，保持實體物件僅僅只有一份是很有意義的。舉個例子，你的應用程式實體 (`UIApplication`) ，應該只有一個吧，顯然是指你的現在當下執行的應用程式。

還有一個例子：行動裝置的螢幕 (`UIScreen`) 實體也是這樣，所以對於這些類別的情況，有實體存在，但是只想要一個實體物件。

單例模式的應用還有另一種情況：你需要一個全域類別來處理設定資料。我們很容易通過單例模式實現安全的執行緒實體存取，而如果有多個類別可以同時存取設定文件，那可就複雜多了。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://wilden-chen.gitbook.io/swift-design-patterns/singleton.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
