美文网首页
python单例模式

python单例模式

作者: _Him | 来源:发表于2018-08-28 17:01 被阅读0次

单例模式:即是一个类只有一个实例,即使创建了多个最终的结果还是会指向第一个创建的这个。

应用场景:1.python web的登录注册的时候打开链接,单例模式可以使不管你打开多少次链接   最后弹出来的只有一个,避免重复出现链接造成内存不必要的损耗。

实现方式:

1.使用模块实现:


class page_inf(object):

    def foo(self):

        pass

information=page_inf()

#保存在page_inf.py中 然后

from page_inf import information

information.foo()


2.装饰器实现


def singleton(cls):

    _instance={}

    def _singleton(*args,**kargs):

        if cls is not in _instance:

            _instance[cls]=cls(*args,**kargs)

        return _instance[cls]

return _singleton

@singleton

class A(object):

    pass

a=A()


3.使用基类


class singleton(object):

    def __new__(cls,*args,**kargs):

        if not hasattr(cls,'_instance'):

            cls._instance=super(singleton,cls).__new__(cls,*args,**kargs)

        return cls._instance

class foo(singleton):

    pass

foo1=foo()


4.使用元类

class singleton(type):

    def __call__(cls,*args,**kargs):

        if not in hasattr(cls,'_instance'):

            cls._instance=super(singleton,cls).__call__(cls,*args,**kargs)

        return cls._instance

class FOO(object):

    __metaclass=singleton

foo=FOO()

相关文章

  • python之理解单例模式

    python之理解单例模式 1、单例模式 单例模式(Singleton Pattern)是一种常见的软件设计模式,...

  • python中OOP的单例

    目录 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 单例

    目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 2018-06-19 Python中的单例模式的几种实现方式的及

    转载自: Python中的单例模式的几种实现方式的及优化 单例模式 单例模式(Singleton Pattern)...

  • python 单例

    仅用学习参考 目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计...

  • 基础-单例模式

    单例模式总结-Python实现 面试里每次问设计模式,必问单例模式 来自《Python设计模式》(第2版) 1.理...

  • python单例模式

    python单例模式实现方式 使用模板 python模块是天然的单例模式(.pyc文件的存在) 使用__new__...

  • 一套完整Python经典面试题,实力派,做内容不做标题党!

    文末含Python学习资料 1:Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例...

  • Python 面向对象7: 单例模式

    一、内容 1.1、单例设计模式 1.2、__new__方法 1.3、Python 中的单例 二、单例设计模式 2....

  • Python设计模式 之 Borg模式

    Borg模式 是单例模式在python中的变种。传统单例模式在python中,存在继承兄弟类之间状态隔离的问题。 ...

网友评论

      本文标题:python单例模式

      本文链接:https://www.haomeiwen.com/subject/hejqwftx.html