python实现单例模式

  1. 使用__new__来实现
#!usr/bin/python
# -*- coding:utf8 -*-


class Singleton(object):
    def __init__(self, name):
        self.name = name

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


one = Singleton('aa')
two = Singleton('bb')
print(one.name, two.name)
print(one is two, id(one) == id(two)) # True True

我们可以看到,在__new__中创建对象的时候, 会先判断该类有没有_instance类属性, 没有则赋值object对象,因此是单例的

  1. 给方法1加上锁,保证线程安全
#!usr/bin/python
# -*- coding:utf8 -*-
# 加上锁
import time
import threading


class Singleton(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        time.sleep(1)
        print(self)

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


def task():
    obj = Singleton()
    print(id(obj))


for i in range(10):
    t = threading.Thread(target=task)
    t.start()
  1. 使用类方法
#!usr/bin/python
# -*- coding:utf8 -*-
# 利用类实现单例模式 支持多线程的单例模式
import time
import threading


class Singleton(object):
    _instance_lock = threading.Lock()
    def __init__(self):

        time.sleep(1)

    @classmethod
    def instance(cls, *args, **kwargs):
        with cls._instance_lock:
            if not hasattr(Singleton, '_instance'):
                Singleton._instance = Singleton()
                return Singleton._instance
            return Singleton._instance


def task():

    obj = Singleton.instance()
    print(obj)


for i in range(10):
    t = threading.Thread(target=task)
    t.start()

你可能感兴趣的:(Python)