- 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
推薦閱讀
- 演進(jìn)式架構(gòu)(原書第2版)
- VMware View Security Essentials
- 數(shù)據(jù)庫(kù)原理及應(yīng)用(Access版)第3版
- Python數(shù)據(jù)分析基礎(chǔ)
- Vue.js 2 and Bootstrap 4 Web Development
- 構(gòu)建移動(dòng)網(wǎng)站與APP:HTML 5移動(dòng)開發(fā)入門與實(shí)戰(zhàn)(跨平臺(tái)移動(dòng)開發(fā)叢書)
- 從程序員到架構(gòu)師:大數(shù)據(jù)量、緩存、高并發(fā)、微服務(wù)、多團(tuán)隊(duì)協(xié)同等核心場(chǎng)景實(shí)戰(zhàn)
- Mastering Python Scripting for System Administrators
- BeagleBone Media Center
- MATLAB 2020 從入門到精通
- 深入理解Java7:核心技術(shù)與最佳實(shí)踐
- 從學(xué)徒到高手:汽車電路識(shí)圖、故障檢測(cè)與維修技能全圖解
- 數(shù)據(jù)結(jié)構(gòu)(C語(yǔ)言)
- NetBeans IDE 8 Cookbook
- Python項(xiàng)目實(shí)戰(zhàn)從入門到精通