一、单例模式

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之单例模式总结的更多相关文章

  1. python实现单例模式的三种方式及相关知识解释

    python实现单例模式的三种方式及相关知识解释 模块模式 装饰器模式 父类重写new继承 单例模式作为最常用的设计模式,在面试中很可能遇到要求手写.从最近的学习python的经验而言,singlet ...

  2. Python 基于python实现单例模式

    基于python实现单例模式 by:授客 QQ:1033553122   概念 简单说,单例模式(也叫单件模式)的作用就是保证在整个应用程序的生命周期中,任何一个时刻,单例类的实例都只存在一个(当然也 ...

  3. python 以单例模式封装logging相关api实现日志打印类

    python 以单例模式封装logging相关api实现日志打印类   by:授客QQ:1033553122 测试环境: Python版本:Python 2.7   实现功能: 支持自由配置,如下lo ...

  4. python的单例模式:

    python的单例模式:http://funhacks.net/2017/01/17/singleton/ https://www.cnblogs.com/huchong/p/8244279.html ...

  5. 【Python】单例模式Singleton

    前两天一个面试被问到python中单例模式有几种实现方式,只答出了可以用元类实现...然后就想不起来了. 之后翻书,原来这些之前都见过的啊.... 1.手动实现真正创建实例的方法__new__()来实 ...

  6. 浅谈Python设计模式 - 单例模式

    本篇主要介绍一下关于Python的单例模式,即让一个类对象有且只有一个实例化对象. 一.使用__new__方法(基类) 要实现单例模式,即为了让一个类只能实例化一个实例,那么我们可以去想:既然限制创建 ...

  7. 【python】Python的单例模式

    原文:http://blog.csdn.net/ghostfromheaven/article/details/7671853 单例模式:保证一个类仅有一个实例,并提供一个访问他的全局访问点. 实现某 ...

  8. python实现单例模式

    有这么一种场景,我们把数据封装到类体或类的某个方法里,然而我们new出这个类只是为了拿到这部分数据,那么当多次这样调用的时候,每次都来拿数据并放到内存中大大浪费了内存. 那我们就可以想,我们拿到一次数 ...

  9. Python 实现单例模式的一些思考

    一.问题:Python中如何实现单例模式 单例模式指一个类只能实例化一个对象. 二.解决方案: 所有资料参考于: http://python.jobbole.com/87294/ https://ww ...

  10. python之单例模式、栈、队列和有序字典

    一.单例模式 import time import threading class Singleton(object): lock = threading.RLock() # 定义一把锁 __inst ...

随机推荐

  1. proguard-project.txt和project.properties混淆代码

     [转]利用android proguard混淆代码 防止反编译,优化代码 网上虽然有很多相关博客,不过貌似都不是最新版的..于是百度+谷歌+github上的开源demo,终于成功的配置了androi ...

  2. M - Tempter of the Bone(DFS,奇偶剪枝)

    M - Tempter of the Bone Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & % ...

  3. B - Catch That Cow (抓牛)

    B - Catch That Cow Time Limit:2000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u ...

  4. 将方法定义在prototype上的好处

    通常js类定义和使用的是这样的: var Class=function(){}; Class.prototype.sharedFn=function(){}; var instanceA=new Cl ...

  5. Redis持久化之rdb&aof

    Redis有两种持久化的方式:快照(RDB文件)和追加式文件(AOF文件) RDB持久化方式是在一个特定的间隔保存某个时间点的一个数据快照. AOF(Append only file)持久化方式则会记 ...

  6. 使用 mock 测试

    参考文章:https://semaphoreci.com/community/tutorials/getting-started-with-mocking-in-python What are the ...

  7. linux环境配置nginx导致页面不刷新

    在linux环境下,配置了nginx负载均衡,由于可能在虚拟主机的配置文件nginx.conf中,对缓存机制未配置成功,导致页面不刷新,仍然显示缓存中的内容. 最后通过注释nginx.conf文件中的 ...

  8. [转] CentOS---网络配置详解

    原文地址: http://blog.chinaunix.net/uid-26495963-id-3230810.html 一.配置文件详解在RHEL或者CentOS等Redhat系的Linux系统里, ...

  9. django路由系统之反向生成url

    from niubin.service import v1 from django.urls import reverse from django.shortcuts import HttpRespo ...

  10. PAT 天梯赛 L1-009. N个数求和 【模拟】

    题目链接 https://www.patest.cn/contests/gplt/L1-009 思路 每一步每一步 往上加,但是要考虑 溢出,所以用 LONG LONG 而且 每一步 都要约分 才能保 ...