Python单例模式

单例模式

  单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在,当希望在整个系统中,某一个类只能出现一个实例时,单例对象就能在这种场景派上用场.

单例的实现方式一:使用classmethod

IP = '10.1.68.13'
PORT = 8080
import settings
class MySQL:
    __instance = None

    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

    @classmethod
    def from_conf(cls):
        if cls.__instance is None:
            cls.__instance = cls(settings.IP, settings.PORT)
        return cls.__instance


obj1 = MySQL.from_conf()
obj2 = MySQL.from_conf()
obj3 = MySQL.from_conf()
obj4 = MySQL('10.1.68.13', 8080)
print(obj1)
print(obj2)
print(obj3)
print(obj4)

单例的实现方式二:使用装饰器

def singleton(cls):
    _instance = cls(settings.IP,settings.PORT)
    def wrapper(*args,**kwargs):
        if args or kwargs:
            instance = cls(*args,**kwargs)
            return instance
        return _instance
    return wrapper

@singleton #MySQL = singlenton(MySQL)  MySQL = wrapper
class MySQL:
    __instance = None
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

obj1 = MySQL()
obj2 = MySQL()
obj3 = MySQL()
print(obj1)
print(obj2)
print(obj3)

单例的实现方式三:使用元类

class Mymeta(type):
    def __init__(self, class_name, class_bases, class_dic):
        # self = MySQL这个类
        instance = self(settings.IP, settings.PORT)
        self.__instance = instance

    def __call__(self, *args, **kwargs):
        # self = MySQL这个类
        if args or kwargs:
            obj = self.__new__(self)
            self.__init__(obj, *args, **kwargs)
            return obj
        else:
            return self.__instance


class MySQL(metaclass=Mymeta):  # MySQL = Mymeta(..)
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port


a = MySQL()
b = MySQL()
c = MySQL()
d = MySQL('10.6.5.6', 8080)
print(a)
print(b)
print(c)
print(d)

单例的实现方式四:使用模块

  python的模块就是天然的单例模式,因为模块在第一次导入时,就会执行一次,但是之后的导入都直会执行第一次导入的指向,因此,我们只需要把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了

def f1():
    from singleton import instance
    print(instance)

def f2():
    from singleton import instance,MySQL
    print(instance)
    obj=MySQL('1.1.1.3',3302)
    print(obj)

f1()
f2()
import settings

class MySQL:
    print('run....')
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

instance=MySQL(settings.IP,settings.PORT)

单例的实现方式四:使用__new__

class MySQL:
    __instance = None

    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        if cls.__instance == None:
            cls.__instance = super().__new__(cls)
        return cls.__instance
obj1=MySQL()
obj2=MySQL()
obj3=MySQL()
print(obj1)
print(obj2)
print(obj3)

 

 

posted @ 2018-08-28 20:50  Yven  阅读(155)  评论(0编辑  收藏  举报