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)

  • 相关阅读:
    括号匹配的检验
    学习过程中遇到的比较有价值的博客--整理
    Spring+SpringMVC+MyBatis的pom.xml依赖
    Hibernate内容详解
    Struts2的拦截器配置
    Maven构建Struts2项目
    Mybatis增删改查,Demo整合
    简单Java类 全网最详细讲解 !!!
    Javaoop 遇到的问题
    Bootstrap 前端框架 遇到的问题 解决方案
  • 原文地址:https://www.cnblogs.com/fmgao-technology/p/9127869.html
Copyright © 2011-2022 走看看