美文网首页
单例模式和装饰器

单例模式和装饰器

作者: nine_9 | 来源:发表于2018-03-26 17:48 被阅读13次

    1 使用__new__方法

    class Singleton(object):

        def __new__(cls, *args, **kw):

            if not hasattr(cls, '_instance'):

                orig = super(Singleton, cls)

                cls._instance = orig.__new__(cls, *args, **kw)

            return cls._instance

    class MyClass(Singleton):

        a = 1

    >>> one = MyClass()

    >>> two = MyClass()

    >>> one == two

    True

    >>> one is two

    True

    >>> id(one), id(two)

    (4303862608, 4303862608)

    2 共享属性

    创建实例时把所有实例的__dict__指向同一个字典,这样它们具有相同的属性和方法.

    class Borg(object):

        _state = {}

        def __new__(cls, *args, **kw):

            ob = super(Borg, cls).__new__(cls, *args, **kw)

            ob.__dict__ = cls._state

            return ob

    class MyClass2(Borg):

        a = 1

    3 装饰器版本

    def singleton(cls, *args, **kw):

        instances = {}

        def getinstance():

            if cls not in instances:

                instances[cls] = cls(*args, **kw)

            return instances[cls]

        return getinstance

    @singleton

    class MyClass:

    装饰器

    def deco(func):

        def _deco():

            print 'before func'

            func()

            print 'after func'

        return _deco

    @deco

    def myfunc():

        print 'myfunc() called'

    myfunc()

    执行结果

    [图片]

    相关文章

      网友评论

          本文标题:单例模式和装饰器

          本文链接:https://www.haomeiwen.com/subject/tcnrcftx.html