最後活躍 2 weeks ago

此 Python 程式碼實作了單例(Singleton)設計模式,確保一個類別在整個應用程式生命週期中只會有一個實例。透過覆寫 __new__ 方法,它保證每次創建該類別的物件時,都將返回同一個已存在的實例,避免重複創建。

timmy 已修改 2 weeks ago. 還原成這個修訂版本

1 file changed, 13 insertions

singleton_pattern.py(檔案已創建)

@@ -0,0 +1,13 @@
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()
11 + b = Singleton()
12 +
13 + print(a is b) # True,同一個
上一頁 下一頁