zoukankan      html  css  js  c++  java
  • Python Day 74 单例模式总结

      ##基于classmethod

    class Mysql(object):
        _instance =None
        def __init__(self,host,port):
            self.host = host
            self.port = port
        @classmethod
        def singleton(cls):
            if not cls._instance:
                cls._instance=cls('127.0.0.1',8000)
            return cls._instance
    obj1=Mysql.singleton()
    obj2=Mysql.singleton()
    obj3=Mysql('192.168.10.1',3306)
    print(id(obj1),id(obj2),id(obj3)) #1475724158400 1475724158400 1475724160304

      ##基于装饰器

    def singelton(cls):
        _instance = cls('127.0.0.1',8000)#先对传入的类实例化一个对象
        def inner(*args,**kwargs):
            if args or kwargs:
                obj = cls(*args,**kwargs)
                return obj
            return _instance
        return inner
    @singelton   #相当于 Mysql = singelton(Mysql)=inner
    class Mysql(object):
        def __init__(self,host,port):
            self.host = host
            self.port = port
    obj1 = Mysql()
    obj2 = Mysql()
    obj3=Mysql('192.168.1.1',3306)
    print(id(obj1),id(obj2),id(obj3))#1744683247040 1744683247040 1744683249112
  • 相关阅读:
    DHTML 动态效果100例
    Apache 发布网站
    Django笔记 3
    JDBC
    Android国行手机使用Google Play Store
    Cloud9 使用 GitHub
    maven
    linux 下查看系统信息的一些命令
    C++成员变量指针和成员函数指针
    SIP 协议
  • 原文地址:https://www.cnblogs.com/liangzhenghong/p/11279551.html
Copyright © 2011-2022 走看看