
- Python 設計模式教程
- Python 設計模式 - 主頁
- 簡介
- Python 設計模式 - 精華
- 模型檢視控制器模式
- Python 設計模式 - 單例
- Python 設計模式 - 工廠
- Python 設計模式 - 建造器
- Python 設計模式 - 原型
- Python 設計模式 - 外觀
- Python 設計模式 - 命令
- Python 設計模式 - 介面卡
- Python 設計模式 - 裝飾器
- Python 設計模式 - 代理
- 責任鏈模式
- Python 設計模式 - 觀察者
- Python 設計模式 - 狀態
- Python 設計模式 - 策略
- Python 設計模式 - 模板
- Python 設計模式 - 享元
- 抽象工廠
- 面向物件
- 面向物件概念實現
- Python 設計模式 - 迭代器
- 字典
- 列表資料結構
- Python 設計模式 - 集合
- Python 設計模式 - 佇列
- 字串和序列化
- Python 中的併發性
- Python 設計模式 - 反
- 異常處理
- Python 設計模式資源
- 快速指南
- Python 設計模式 - 資源
- 討論
Python 設計模式 - 單例
此模式限制類的一個物件例項化。它是一種建立模式,只涉及一個類建立方法和指定的物件。
它提供了一個全域性訪問點來建立例項。

如何實現單例類?
以下程式演示了單例類的實現,它列印多次建立的例項。
class Singleton: __instance = None @staticmethod def getInstance(): """ Static access method. """ if Singleton.__instance == None: Singleton() return Singleton.__instance def __init__(self): """ Virtually private constructor. """ if Singleton.__instance != None: raise Exception("This class is a singleton!") else: Singleton.__instance = self s = Singleton() print s s = Singleton.getInstance() print s s = Singleton.getInstance() print s
輸出
上述程式生成以下輸出 -

建立的例項數量相同,並且輸出中列出的物件沒有差異。
廣告