zoukankan      html  css  js  c++  java
  • 单例模式

    class MySQL:
    __sign = None
    def __init__(self):
    self.host = "127.0.0.1"
    self.port = 3306

    @classmethod
    def signleton(cls):
    if not cls.__sign:
    obj = cls()
    cls.__sign = obj
    return cls.__sign

    def conn(self):
    pass

    m1 = MySQL.signleton()
    m2 = MySQL.signleton()
    print(m1 is m2,"1")

    #但是这样必须调用类方法sighlenton来实例化。

    """
    通过元类实现单例模式
    """


    class MySQLmeta(type):
    __sign = None

    def __call__(self, *args, **kwargs):
    if not MySQLmeta.__sign:
    obj = object.__new__(self)
    self.__init__(obj, *args, **kwargs)
    MySQLmeta.__sign = obj
    return MySQLmeta.__sign


    class MySQL(metaclass=MySQLmeta):
    def __init__(self):
    self.host = "127.0.0.1"
    self.port = 3306

    def conn(self):
    pass

    m1 = MySQL()
    m2 = MySQL()
    print(m1 is m2,"2")


    class MySQLmeta(type):

    def __init__(self, class_name, class_bases, class_dict):
    super(MySQLmeta, self).__init__(class_name, class_bases, class_dict)
    self.__sign = None

    def __call__(self, *args, **kwargs):
    if not self.__sign:
    obj = object.__new__(self)
    self.__init__(obj, *args, **kwargs)
    self.__sign = obj
    return self.__sign


    class MySQL(metaclass=MySQLmeta):
    def __init__(self):
    self.host = "127.0.0.1"
    self.port = 3306

    def conn(self):
    pass

    m1 = MySQL()
    m2 = MySQL()
    print(m1 is m2,"3")

    """
    通过new方法实现单例模式
    """

    class MySQL(metaclass=MySQLmeta):
    __sign = None

    def __new__(cls, *args, **kwargs):
    if not cls.__sign:
    obj = super().__new__(cls, *args, **kwargs)
    cls.__sign = obj
    return cls.__sign

    def __init__(self):
    self.host = "127.0.0.1"
    self.port = 3306

    def conn(self):
    pass

    m1 = MySQL()
    m2 = MySQL()
    print(m1 is m2,"4")
  • 相关阅读:
    一个简单的NodeJs静态页面的web服务器
    javascript的use strict(使用严格模式)
    javascript声明对象时 带var和不带var的区别
    javascript对象的属性,方法,prototype作用范围分析.
    linux下两台服务器文件实时同步方案设计和实现
    Memcache mutex设计模式
    php内存管理
    php-fpm 和 mysql 之间的关系
    innoDB 下主键的思考
    哈希表的实现
  • 原文地址:https://www.cnblogs.com/walle-zhao/p/10775964.html
Copyright © 2011-2022 走看看