1. 程式人生 > >單例模式連結資料庫

單例模式連結資料庫

主要思想是利用類方法或者類屬性建立例項,在建立之前做一個判斷:

1)使用__new__ 方法

import pymysql


class Singleton(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self):
        self.conn = pymysql.connect(host='127.0.0.1', user='root', password='root', database='job',
                                    charset='utf8')


if __name__ == '__main__':
    a = Singleton()
    b = Singleton()
    print(a.conn, b.conn)

執行輸出結果是:

<pymysql.connections.Connection object at 0x102694ef0> <pymysql.connections.Connection object at 0x102694ef0>

可以看到兩個連線都是同一個例項

但是我有疑問,如果例項化要傳參,呼叫__init__初始化的,老是報錯,求大神們解答

import pymysql


class Singleton(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instance


class A(Singleton):
    def __init__(self, name):
        self.conn = pymysql.connect(host='127.0.0.1', user='root', password='root', database='job',
                                    charset='utf8')
        self.name = name


if __name__ == '__main__':
    apple = A('apple')
    banana = A('banana')
Traceback (most recent call last):
  File "/Users/daniel/Documents/test/singleton.py", line 19, in <module>
    apple = A('apple')
  File "/Users/daniel/Documents/test/singleton.py", line 7, in __new__
    cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
TypeError: object() takes no parameters

另一種是用方法定義

class Singleton(object):
    _instance = None

    def __init__(self, name):
        self.name = name

    @classmethod
    def get_instance(cls, name):
        if cls._instance:
            return cls._instance
        else:
            obj = cls(name)
            cls._instance = obj
            return obj


if __name__ == '__main__':
    _a = Singleton.get_instance('apple')
    _b = Singleton.get_instance('banana')
    print(_a, _b)

結果如下:

<__main__.Singleton object at 0x10205bd30> <__main__.Singleton object at 0x10205bd30>

總覺得用類方法感覺不夠統一,能不能解決__new__建立單例傳參的問題呢?可能是py2 和py3的區別吧

參考了文章:

程式碼如下:

import pymysql


class Singleton(object):
    _instance = None

    def __new__(cls, name):
        if not cls._instance:
            cls._instance = object.__new__(cls)
        return cls._instance


class A(Singleton):
    def __init__(self, name):
        self.name = name
        self.conn = pymysql.connect(host='127.0.0.1', user='root', password='root', database='job',
                                    charset='utf8')


if __name__ == '__main__':
    a = A('apple')
    b = A('bnana')
    print(a, b)

執行結果:

<__main__.A object at 0x10205bf28> <__main__.A object at 0x10205bf28>