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
  • 相关阅读:
    设计模式学习笔记一
    linux学习记录(一)
    eclipse插件集合
    什么叫反向代理?
    shiro学习四
    shiro学习三
    shiro学习二
    第二次作业
    第一次作业
    自我介绍
  • 原文地址:https://www.cnblogs.com/liangzhenghong/p/11279551.html
Copyright © 2011-2022 走看看