- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章Python中单例模式总结由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
1、单例模式 。
a、单例模式分为四种:文件,类,基于__new__方法实现单例模式,基于metaclass方式实现 。
b、类实现如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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__方法实现单例模式 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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__方法) 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
# 第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)
|
原文链接:https://www.cnblogs.com/mengqingjian/p/8453975.html 。
最后此篇关于Python中单例模式总结的文章就讲到这里了,如果你想了解更多关于Python中单例模式总结的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!