37)django-单例模式

一:单例模式

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

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

  常用例子:数据库连接串,只保存一个,或者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 一样
原文地址:https://www.cnblogs.com/lixiang1013/p/8011525.html