单例模式与多例模式最主要的区别是:
单例模式是一个类只有单个对象被创建
多例模式是一个类可以有多个对象被创建
一、单例模式创建
下面展示单例模式的创建过程:
1.通过类方法创建
#!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: admin
@file: 类方法.py
@time: 2021/05/24
@desc:
"""
class Custom():
def __init__(self, name):
import time
time.sleep(1)
self.name = name
# 通过类方法创建实例
@classmethod
def creat_class(cls, *args, **kwargs):
# 如果没有对象
if not hasattr(Custom, "_instance"):
Custom._instance = Custom(*args, **kwargs)
return Custom._instance
# # 通过类方法来创建类的实例化对象
c1 = Custom.creat_class('张三')
c2 = Custom.creat_class('李四')
print(c1)
print(c2)
print(c1 is c2) # True
<__main__.Custom object at 0x000002B8CD45F708>
<__main__.Custom object at 0x000002B8CD45F708>
True
但是,使用多线程时,使用类方法创建就会出现问题
#!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: admin
@file: 类方法.py
@time: 2021/05/24
@desc:
"""
import threading
import time
class Custom():
def __init__(self, name):
import time
time.sleep(1)
self.name = name
# 通过类方法创建实例
@classmethod
def creat_class(cls, *args, **kwargs):
# 如果没有对象
if not