官术网_书友最值得收藏!

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
主站蜘蛛池模板: 苍梧县| 曲松县| 剑川县| 藁城市| 曲麻莱县| 湟中县| 沾化县| 垣曲县| 清镇市| 宁阳县| 苏尼特右旗| 邵东县| 石林| 三亚市| 宝清县| 炉霍县| 运城市| 奉新县| 桐柏县| 山东| 永修县| 韶关市| 凉山| 峡江县| 华蓥市| 施甸县| 合阳县| 庆城县| 汉中市| 天柱县| 玉林市| 揭西县| 乡城县| 五峰| 呼图壁县| 泾川县| 四会市| 江津市| 安义县| 大港区| 澄城县|