1.单例模式的实现方式
'''
单例模式: (面试让你手撸,一定要背下来。)
1.通过classmethod
2.通过装饰器实现
3.通过__new__实现
4.通过导入模块时实现
5.通过元类实现。
'''
2.通过classmetod实现单例模式
import settings
# 通过classmethod
class MySQL:
# 一个默认值,用于判断对象是否存在, 对象不存在证明值是None
# __instance是类的属性,可以由类来调用
__instance = None # ---》 执行到代码的57行 ---》 obj
# __instance = obj
def __init__(self, host, port):
self.host = host
self.port = port
@classmethod
def singleton(cls, host, port): # 单例方法 ---》 类方法
# 判断__instance中若没有值,证明没有对象
if not cls.__instance:
# 产生一个对象并返回
obj = cls(host, port)
# None ---> obj
cls.__instance = obj
# 若__instance中有值,证明对象已经存在,则直接返回该对象
return cls.__instance
def start_mysql(self):
print('启动mysql')
def close(self):
print('关闭mysql')
obj1 = MySQL.singleton(settings.HOST, settings.PORT)
obj1.start_mysql()
print(obj1)
obj2 = MySQL.singleton(settings.HOST, settings.PORT)
print(obj2)