zoukankan      html  css  js  c++  java
  • 单例实现方式

    #!/usr/bin/env python
    # encoding: utf-8  
    # Date: 2018/6/3

    # 实现方式一:
    # 基于元类控制类的实例行为,单例模式

    # class MySQL:
    #     __instance=None
    #
    #     def __init__(self):
    #         self.host = '127.0.0.1'
    #         self.port = 3306
    #
    #     #单例创建类
    #     @classmethod
    #     def singleton(cls):
    #         if not cls.__instance:
    #             obj=cls()
    #             cls.__instance = obj
    #         return cls.__instance
    #
    #     def conn(self):
    #         pass
    #
    #     def execute(self):
    #         pass
    #
    #
    # # obj1 = MySQL()
    # # obj2 = MySQL()
    # #
    # # print(obj1)
    # # print(obj2)
    #
    # # 单例产生类
    # obj1 = MySQL.singleton()

    # 实现方式二:元类方式


    class Mymeta(type):
        def __init__(self, class_name, class_bases, class_dic):
            if not class_name.istitle():
                raise TypeError('类名的首字母必须大写')
            if '__doc__' not in class_dic or not class_dic['__doc__'].strip():
                raise TypeError('必须有注释,且注释不能为空')
            super(Mymeta, self).__init__(class_name, class_bases, class_dic)
            self.__instance = None

        def __call__(self, *args, **kwargs):  # obj = Chinese('egon', age=18)
            if not self.__instance:
                obj = object.__new__(self)
                self.__init__(obj)
                self.__instance = obj
            return self.__instance


    class Mysql(object, metaclass=Mymeta):
        '''
        123456
        '''
        def __init__(self):
            self.host = '127.0.0.1'
            self.port = 3306

        def conn(self):
            pass

        def execute(self):
            pass


    obj1 = Mysql()
    obj2 = Mysql()
    obj3 = Mysql()

    print(obj1 is obj2 is obj3)

  • 相关阅读:
    AJAX异步交互
    Java 异常讲解(转)
    Spring 配置文件详解 (以2.5为例)
    Java 获取当前系统时间方法比较
    Cannot change version of project facet Dynamic web module to 3.0
    使用 GCC 调试程序
    汇编 内存段划分和寄存器
    java.lang.StringBuilder
    java.lang.String
    建立和断开与MySQL服务器的连接
  • 原文地址:https://www.cnblogs.com/fmgao-technology/p/9127869.html
Copyright © 2011-2022 走看看