- Learning Python Design Patterns(Second Edition)
- Chetan Giridhar
- 158字
- 2021-07-16 09:46:15
Lazy instantiation in the Singleton pattern
One of the use cases for the Singleton pattern is lazy instantiation. For example, in the case of module imports, we may accidently create an object even when it's not needed. Lazy instantiation makes sure that the object gets created when it's actually needed. Consider lazy instantiation as the way to work with reduced resources and create them only when needed.
In the following code example, when we say s=Singleton()
, it calls the __init__
method but no new object gets created. However, actual object creation happens when we call Singleton.getInstance()
. This is how lazy instantiation is achieved.
class Singleton: __instance = None def __init__(self): if not Singleton.__instance: print(" __init__ method called..") else: print("Instance already created:", self.getInstance()) @classmethod def getInstance(cls): if not cls.__instance: cls.__instance = Singleton() return cls.__instance s = Singleton() ## class initialized, but object not created print("Object created", Singleton.getInstance()) # Object gets created here s1 = Singleton() ## instance already created
推薦閱讀
- Learning Microsoft Windows Server 2012 Dynamic Access Control
- Getting started with Google Guava
- 數據庫原理及應用(Access版)第3版
- Xcode 7 Essentials(Second Edition)
- MySQL 8 DBA基礎教程
- 網頁設計與制作教程(HTML+CSS+JavaScript)(第2版)
- Python Geospatial Development(Second Edition)
- 大學計算機基礎實驗指導
- WordPress 4.0 Site Blueprints(Second Edition)
- Java系統化項目開發教程
- 零基礎學Kotlin之Android項目開發實戰
- Android群英傳
- 3D Printing Designs:Design an SD Card Holder
- 新手學ASP.NET 3.5網絡開發
- Java Web程序開發參考手冊