python 单例模式

单例模式,也叫单子模式,是一种常用的软件设计模式。在应用这个模式时,单例对象的类必须保证只有一个实例存在

用装饰器方式实现单例模式

#!/usr/bin/python
# coding=utf-8


def wrapper(cls):
    instances = {}

    def inner():
        if cls not in instances:
            instances[cls] = cls()
        return cls

    return inner


@wrapper
def Foo():
    pass


f1 = Foo()
f2 = Foo()

print(f1 is f2)

用静态方法实现单例模式

#!/usr/bin/python
# coding=utf-8


class ConnectPool:
    __instatnce = None

    @staticmethod
    def get_instance():
        if ConnectPool.__instatnce:
            return ConnectPool.__instatnce
        else:
            ConnectPool.__instatnce = ConnectPool()
            return ConnectPool.__instatnce


obj1 = ConnectPool.get_instance()
obj2 = ConnectPool.get_instance()
print(obj1 is obj2)

  


***微信扫一扫,关注“python测试开发圈”,了解更多测试教程!***
posted @ 2017-01-02 12:51  鲨鱼逛大街  阅读(280)  评论(0编辑  收藏  举报