1.什么是单例:
单例模式是指在内存中只会创建且仅创建一次对象的设计模式。在程序中多次使用同一个对象且作用相同时,为了防止频繁地创建对象使得内存飙升,单例模式可以让程序仅在内存中创建一个对象,让所有需要调用的地方都共享这一单例对象。
2.代码实现:
class Singleton:
__instence = None
def __new__(cls, *args, **kwargs):
if cls.__instence is None:
cls.__instence = object.__new__(cls)
return cls.__instence
singleton1 = Singleton()
singleton2 = Singleton()
print(id(singleton1))
print(id(singleton2))
结果图: