python 单例模式总结
# 第一种方法 new 方法
class Singleton(object):
def __new__(cls,*args,**kw):
if not hasattr(cls,'_instance'):
cls._instance = super(Singleton,cls).__new__(cls,*args,**kw)
return cls._instance
s1 = Singleton()
s2 = Singleton()
s1 == s2
# 第二种方法升级为元类 call 控制,实质跟方法一差不多
class SingletonMetaclass(type):
def __call__(cls,*args,**kw):
if not hasattr(cls,'_instance'):
cls._instance = super(SingletonMetaclass,cls).__call__(*args,**kw)
# cls.__init__(cls._instance,*args,**kw)
return cls._instance
class Singleton(object,metaclass=SingletonMetaclass):
pass
s1 = Singleton()
s2 = Singleton()
s1 == s2
# 第三种,使用装饰器
def singleton(cls,*args,**kw):
instance = {}
def get_instance():
if cls not in instance:
instance[cls] = cls.__new__(cls,*args,**kw)
return instance[cls]
return get_instance
@singleton
class Singleton(object):
pass
s1 = Singleton()
s2 = Singleton()
s1 == s2
线程安全
# 线程安全的 写法
# 装饰器
import threading
def Singleton(cls,*args,**kw):
instance = {}
_instance_lock = threading.Lock()
def get_instance():
if cls not in instance:
with _instance_lock:
if cls not in instance:
instance[cls] = cls.__new__(cls,*args,**kw)
cls.__init__(instance[cls],*args,**kw)
return instance[cls]
return get_instance
@Singleton
class Demo(object):
pass
d1 = Demo()
d2 = Demo()
d1 is d2
# 基类
class Singleton(object):
def __new__(cls,*args,**kw):
if not hasattr(cls,'_instance'):
cls._instance = super(Singleton,cls).__new__(cls,*args,**kw)
return cls._instance
s1 = Singleton()
s2 = Singleton()
print(s1 == s2)
# 升级为元类
import threading
class SingletonMetaclass(type):
def __call__(cls,*args,**kw):
_instance_lock = threading.Lock()
if not hasattr(cls,'_instance'):
with _instance_lock:
if not hasattr(cls,'_instance'):
cls._instance = cls.__new__(cls,*args,**kw)
cls.__init__(cls._instance,*args,**kw)
return cls._instance
class Demo(object,metaclass=SingletonMetaclass):
pass
d2 = Demo()
d3 = Demo()
d2 is d3
mysingleton.py
class Singleton(object):
def foo(self):
pass
singleton = Singleton()
将上面的代码保存在文件 mysingleton.py 中,要使用时,直接在其他文件中导入此文件中的对象,这个对象即是单例模式的对象
from mysingleton import singleton
方法四:Borg模式
利用“类变量对所有对象唯一”,即__share_state
class Foo:
__share_state = {}
def __init__(self):
self.__dict__ = self.__share_state
python 单例模式总结的更多相关文章
- python 单例模式获取IP代理
python 单例模式获取IP代理 tags:python python单例模式 python获取ip代理 引言:最近在学习python,先说一下我学Python得原因,一个是因为它足够好用,完成同样 ...
- Python 单例模式讲解
Python 单例模式讲解 本节内容: classmethod用途 单例模式方法一 类__new__方法讲解 单例模式方法二 前言: 使用单例方法的好处:对于一个类,多次实例化会产生多个对象,若使用单 ...
- python单例模式的实现与优化
python单例模式的实现与优化 阅读目录(Content) 单例模式 实现单例模式的几种方式 1.使用模块 2.使用装饰器 3.使用类 4.基于__new__方法实现(推荐使用,方便) 5.基于me ...
- python 单例模式
单例模式,也叫单子模式,是一种常用的软件设计模式.在应用这个模式时,单例对象的类必须保证只有一个实例存在 用装饰器方式实现单例模式 #!/usr/bin/python # coding=utf-8 d ...
- Python单例模式
1.单例模式介绍 单例模式,也叫单子模式,是一种常用的软件设计模式.在应用这个模式时, 单例对象的类必须保证只有一个实例存在.许多时候整个系统只需要拥有一个 全局对象,这样有利于我们协调系统整体的行为 ...
- python 单例模式的四种创建方式
单例模式 单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在.当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场. ...
- python 单例模式的四种实现方法及注意事项
一.模块单例 Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码. #foo1.py clas ...
- python 单例模式,一个类只能生成唯一的一个实例,重写__new__方法详解
单例:一个类只能生成唯一的一个实例 每个类只要被实例化了,他的私有属性 '_instance'就会被赋值,这样理解对吗 对 #方法1,实现__new__方法 #并在将一个类的实例绑定到类变量_inst ...
- 设计模式(Python)-单例模式
本系列文章是希望将软件项目中最常见的设计模式用通俗易懂的语言来讲解清楚,并通过Python来实现,每个设计模式都是围绕如下三个问题: 为什么?即为什么要使用这个设计模式,在使用这个模式之前存在什么样的 ...
- Python单例模式的四种方法
在这之前,先了解super()和__new__()方法 super()方法: 返回一个父类或兄弟类类型的代理对象,让你能够调用一些从继承过来的方法. 它有两个典型作用: a. 在单继承的类层次结构中, ...
随机推荐
- django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
报错现象 django 启动的时候报错 django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. 报错解决 记不清是我有毛 ...
- Java io概述
内容来源:http://ifeve.com/java-io/ Java IO 概述 输入流可以理解为向内存输入,输出流可以理解为从内存输出 Java的IO包主要关注的是从原始数据源的读取以及输出原始数 ...
- iview 模态框点击确定按钮不消失
<div slot="footer"> <Button type="text" size="large" @click=& ...
- A1137. Final Grading
For a student taking the online course "Data Structures" on China University MOOC (http:// ...
- poj 2229 Sumsets(记录结果再利用的DP)
传送门 https://www.cnblogs.com/violet-acmer/p/9852294.html 题意: 将一个数N分解为2的幂之和共有几种分法? 题解: 定义dp[ i ]为数 i 的 ...
- POJ 2528 Mayor's posters (线段树+离散化)
Mayor's posters Time Limit: 1000MS Memory Limit: 65536K Total Submissions:75394 Accepted: 21747 ...
- PHP生成四角图片
<?php /** 圆角 $radius = 100; $img = imagecreatetruecolor($radius, $radius); // 创建一个正方形的图像 $bgcolor ...
- java中Comparatable接口和Comparator接口的区别
1.不同类型的排序规则 .自然排序是什么? 自然排序是一种升序排序.对于不同的数据类型,升序规则不一样: BigDecimal BigInteger Byte Double Float Int ...
- (去重 sort)nyoj8-一种排序
8-一种排序 内存限制:64MB 时间限制:3000ms 特判: No通过数:235 提交数:749 难度:3 题目描述: 现在要求按照以下方式排序(默认排序都是从小到大) 现在有很多长方形,每一个长 ...
- Django+Uwsgi+Nginx
一.数据库准备 yum install mariadb-server -y systemctl start mariadb 监听端口 netstat -lntup mysql 进入 grant ...