Python之单例模式总结
一、单例模式
a、单例模式分为四种:文件,类,基于__new__方法实现单例模式,基于metaclass方式实现
b、类实现如下:
class Sigletion(objects):
import time
def __init__(self):
time.sleep(1)
@classmethod
def instance(cls,*args,**kwargs)
if not hasattr(Sigletion,'_instance'):
Sigletion._instance=Sigletion(*args,**kwargs)
return Sigletion._instance import threading daf task(arg):
obj=Sigletion.instance()
print(obj) for i in range(10):
t=threading.Thread(target=task,args=[i,])
t.start()
c、基于__new__方法实现单例模式
import time
import threading
class Singleton(object):
_instance_lock=threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(Singleton,"_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton,"_instance"):
Singleton._instance=object.__new__(cls,*args,**kwargs)
return Singleton._instance obj1=Singleton()
obj2=Singleton()
print(obj1,obj2) def task(arg):
obj = Singleton()
print(obj) for i in range(10):
t = threading.Thread(target=task,args=[i,])
t.start()
d、基于metaclass方式实现单例模式
"""
1.对象是类创建,创建对象时候类的__init__方法自动执行,对象()执行类的 __call__ 方法
2.类是type创建,创建类时候type的__init__方法自动执行,类() 执行type的 __call__方法(类的__new__方法,类的__init__方法) # 第0步: 执行type的 __init__ 方法【类是type的对象】
class Foo:
def __init__(self):
pass def __call__(self, *args, **kwargs):
pass # 第1步: 执行type的 __call__ 方法
# 1.1 调用 Foo类(是type的对象)的 __new__方法,用于创建对象。
# 1.2 调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。
obj = Foo()
# 第2步:执行Foodef __call__ 方法
obj()
"""
import threading class SingletonType(type):
_instace_lock=threading.Lock()
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with SingletonType._instace_lock:
if not hasattr(cls, "_instance"):
cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
return cls._instance
class Foo(metaclass=SingletonType):
def __init__(self,name):
self.name=name obj1 = Foo('name')
obj2 = Foo('name')
print(obj1,obj2)
Python之单例模式总结的更多相关文章
- python实现单例模式的三种方式及相关知识解释
python实现单例模式的三种方式及相关知识解释 模块模式 装饰器模式 父类重写new继承 单例模式作为最常用的设计模式,在面试中很可能遇到要求手写.从最近的学习python的经验而言,singlet ...
- Python 基于python实现单例模式
基于python实现单例模式 by:授客 QQ:1033553122 概念 简单说,单例模式(也叫单件模式)的作用就是保证在整个应用程序的生命周期中,任何一个时刻,单例类的实例都只存在一个(当然也 ...
- python 以单例模式封装logging相关api实现日志打印类
python 以单例模式封装logging相关api实现日志打印类 by:授客QQ:1033553122 测试环境: Python版本:Python 2.7 实现功能: 支持自由配置,如下lo ...
- python的单例模式:
python的单例模式:http://funhacks.net/2017/01/17/singleton/ https://www.cnblogs.com/huchong/p/8244279.html ...
- 【Python】单例模式Singleton
前两天一个面试被问到python中单例模式有几种实现方式,只答出了可以用元类实现...然后就想不起来了. 之后翻书,原来这些之前都见过的啊.... 1.手动实现真正创建实例的方法__new__()来实 ...
- 浅谈Python设计模式 - 单例模式
本篇主要介绍一下关于Python的单例模式,即让一个类对象有且只有一个实例化对象. 一.使用__new__方法(基类) 要实现单例模式,即为了让一个类只能实例化一个实例,那么我们可以去想:既然限制创建 ...
- 【python】Python的单例模式
原文:http://blog.csdn.net/ghostfromheaven/article/details/7671853 单例模式:保证一个类仅有一个实例,并提供一个访问他的全局访问点. 实现某 ...
- python实现单例模式
有这么一种场景,我们把数据封装到类体或类的某个方法里,然而我们new出这个类只是为了拿到这部分数据,那么当多次这样调用的时候,每次都来拿数据并放到内存中大大浪费了内存. 那我们就可以想,我们拿到一次数 ...
- Python 实现单例模式的一些思考
一.问题:Python中如何实现单例模式 单例模式指一个类只能实例化一个对象. 二.解决方案: 所有资料参考于: http://python.jobbole.com/87294/ https://ww ...
- python之单例模式、栈、队列和有序字典
一.单例模式 import time import threading class Singleton(object): lock = threading.RLock() # 定义一把锁 __inst ...
随机推荐
- Palindrome Function
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 256000/256000 K (Java/Others)Total Submissio ...
- Using InfluxDB in Grafana,influxDB在grafana中使用
grafana带有功能丰富的数据源插件influxDB.支持丰富的查询编辑器.注释和templating(模版)查询. 增加数据源(Adding the data source) 点击顶部Grafan ...
- MYSQL中case when then else end 用法
条件语句 delimiter \\CREATE PROCEDURE proc_if ()BEGIN declare i int default 0; if i = 1 THEN ...
- spring 编译时抱错纪录class path resource [spring/] cannot be resolved to URL because it does not exist
class path resource [spring/] cannot be resolved to URL because it does not exist; 在 pom.xml 里添加如下代码 ...
- OpenCV3计算机视觉+Python(五)
人脸检测和识别 本章将介绍Haar级联分类器,通过对比分析相邻图像区域来判断给定图像或子图像与已知对象是否匹配.本章将考虑如何将多个Haar级联分类器构成一个层次结构,即一个分类器能识别整体区域(如人 ...
- Happy Hours, Happy Days
No matter our age, being happy creates more happiness--making a better world for all of us. 无论青春与否,让 ...
- 用数据池来实现socket并发
最终目标:启动服务后可以有无数个访问,并且可以随时输入,服务端使用进程池. 服务端 from socket import * import os,time from concurrent.future ...
- JS编写类似弹出窗口样式显示层
JSp中增加div <!-- 提交变更申请 --> <div id="changeWindow" class="easyui-window" ...
- OC源文件扩展名
常见的文件扩展名 扩展名 含义 扩展名 含义 .c C语言源文件 .mm Objective-C++源文件 .cc..cpp C++源文件 .pl Perl源文件 .h 头文件 .o Object(编 ...
- 'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator.
let newStr = String(str[..<index]) // = str.substring(to: index) In Swift 3 let newStr = String(s ...