此 Python 程式碼實作了單例(Singleton)設計模式,確保一個類別在整個應用程式生命週期中只會有一個實例。透過覆寫 __new__ 方法,它保證每次創建該類別的物件時,都將返回同一個已存在的實例,避免重複創建。
| 1 | class Singleton: |
| 2 | _instance = None |
| 3 | |
| 4 | def __new__(cls): |
| 5 | if cls._instance is None: |
| 6 | cls._instance = super().__new__(cls) |
| 7 | return cls._instance |
| 8 | |
| 9 | |
| 10 | a = Singleton() |