一:单例模式

  单例模式,是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。

  通过单例模式可以保证系统中一个类只有一个实例。即一个类只有一个对象实例.

  常用例子:数据库连接串,只保存一个,或者kindediter等过滤类等。

二:单例模式实现

  方法1:

# -*- coding:utf-8 -*-
__author__ = 'shisanjun'

class Foo(object):
    instance=None

    def __init(self):
        self.name="shisanjun"

    @classmethod
    def get_intance(cls):
        if Foo.instance:
            return Foo.instance
        else:
            Foo.instance=Foo()
            return Foo.instance

    def process(self):
        return "123"

obj1=Foo.get_intance()
obj2=Foo.get_intance()
print(id(obj1),id(obj2))
#结果:44675872 44675872 一样

  方法2:通过__new__方法实现,__new__在__init__前先执行

# -*- coding:utf-8 -*-
__author__ = 'shisanjun'

class Foo(object):
    instance=None

    def __init(self):
        self.name="shisanjun"

    def __new__(cls, *args, **kwargs):
        if Foo.instance:
            return Foo.instance
        else:
            Foo.instance=object.__new__(cls,*args,**kwargs)
            return Foo.instance

    def process(self):
        return "123"

obj1=Foo()
obj2=Foo()
print(id(obj1),id(obj2))
#结果:38187808 38187808 一样

 

相关文章:

  • 2022-12-23
  • 2021-07-10
  • 2021-10-28
  • 2022-12-23
  • 2021-07-14
  • 2022-12-23
  • 2021-12-03
  • 2022-12-23
猜你喜欢
  • 2021-11-29
  • 2021-11-15
  • 2021-09-21
  • 2022-12-23
  • 2021-06-16
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案