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

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
主站蜘蛛池模板: 合江县| 洛阳市| 武夷山市| 宣恩县| 宁海县| 富川| 易门县| 通河县| 泸水县| 维西| 邹城市| 漠河县| 浏阳市| 吉隆县| 五常市| 固安县| 南充市| 海兴县| 怀仁县| 南安市| 甘孜县| 临猗县| 蛟河市| 政和县| 江陵县| 兴仁县| 司法| 垣曲县| 石泉县| 水富县| 丰都县| 吉林市| 类乌齐县| 赤城县| 区。| 南投市| 东乡族自治县| 天镇县| 保山市| 图们市| 嫩江县|