• 单例模式中的四种方式


    1、什么是单例模式?

    单例模式指的是多种不同的实例化指向同一个实例

    2、为何要去用单例模式?

    使用单例模式是为了减少资源的浪费

    3、如何去用单例模式?

    方式一:

    #先写一个setting模块用来存放(ip=None,port=None)
    import setting
    class Mysql:
        __instance=None
        def __init__(self,ip,port):
            self.ip=ip
            self.port=port
        @classmethod
        def srea(cls):
            if cls.__instance is None:
                cls.__instance=cls(setting.ip,setting.port)
            return cls.__instance
    obj=Mysql.srea()
    obj1=Mysql('1.1.1.1',203)
    print(obj)
    print(obj1)

    方式二:

    先写一个setting模块用来存放(ip=None,port=None)
    import setting
    def atuh(cls):
        _instance=cls(setting.ip,setting.port)
        def warpper(*args,**kwargs):
            if args or kwargs:
                obi=cls(*args,**kwargs)
                return obi
            return _instance
        return warpper
    @atuh
    class Mysql:
        def __init__(self,ip,port):
            self.ip=ip
            self.port=port
    obj=Mysql()
    obj1=Mysql()
    obj2=Mysql('1.1.1.1',2206)
    print(obj)
    print(obj1)
    print(obj2)

    方式三:

    先写一个setting模块用来存放(ip=None,port=None)
    import setting
    class Mymeta(type):
        def __init__(self,mysql,mysql_obj,mysql_dic):
            self._instance=self(setting.ip,setting.port)
        def __call__(self, *args, **kwargs):
            if args or kwargs:
                obj=self.__new__(self)
                self.__init__(obj,*args,**kwargs)
                return obj
            else:
                return self._instance
    class Mysql(metaclass=Mymeta):
        def __init__(self,ip,port):
            self.ip=ip
            self.port=port
    obj=Mysql()
    obj1=Mysql()
    obj2=Mysql('1.1.1.3',2206)
    print(obj)
    print(obj1)
    print(obj2)

    方式四:

    先写一个setting模块用来存放(ip=None,port=None)再写一个song模块
    song模块的代码如下:class Mysql:
        def __init__(self,ip,port):
            self.ip=ip
            self.port=port
    instance=Mysql('1.1.1.1',2206)
    主题代码吐下:
    def f():
        from song import instance
        print(instance)
    def f2():
        from song import instance, Mysql
        odj=Mysql('1.1.1.1',2206)
        print(odj)
    f()
    f2()
  • 相关阅读:
    P4097 [HEOI2013]Segment(李超线段树模板)
    P2155 [SDOI2008]沙拉公主的困惑
    BZOJ3675 [Apio2014]序列分割[斜率优化dp]
    hdu4261 Estimation[暴力dp+对顶堆]
    poj2374 Fence Obstacle Course[线段树+DP]
    poj1463 Strategic game[树形DP]
    CH5E02 [IOI1999]花店橱窗[暴力dp]
    CH5E01[NOIP2010] 乌龟棋[暴力]
    CH5702 Count The Repetitions[倍增dp]
    P1081 [NOIP2012]开车旅行[倍增]
  • 原文地址:https://www.cnblogs.com/ageliu/p/9551409.html
Copyright © 2020-2023  润新知