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
  • 相关阅读:
    jQuery教程
    AJAX请求 $.ajax方法的使用
    smarty block_function
    smarty
    位运算版本的交换两数
    提取字符串中的数字
    vue地址插件多级联动自适应 + github地址
    vue插件
    网页title旁边的小图片
    二十三种设计模式[14]
  • 原文地址:https://www.cnblogs.com/liangzhenghong/p/11279551.html
Copyright © 2011-2022 走看看