【通俗说设计模式】五、单例模式 & Python示例

专业介绍:

指一个类只有一个实例,且该类能自行创建这个实例的一种模式。

通俗介绍: 

一个类,我们可以反复创建它的实例,但是,创建N次最终得到的也是同一个实例,占用的资源大小是固定的,这就叫单例模式。

例如Windows上很多对象都是单例模式,比如winows的任务管理器,回收站,文件系统,线程池等待,如果他们可以被创建出多个实例,系统肯定满地bug。

代码:

# 单例模式


# ---------- 装饰器实现单例 ------------
def single(func_or_cls):
    """适用于函数、类的单例创建"""

    def _wrap(*args, **kw):
        if not hasattr(func_or_cls, '_instance'):  # `_instance` 为自定义
            func_or_cls._instance = func_or_cls(*args, **kw)
        return func_or_cls._instance

    return _wrap


@single
class God:
    def __init__(self):
        print('I am only God!')


# ---------- 使用 __new__()实现单例 ------------


class SingleGod:
    def __init__(self):
        """如果已经有一个实例,这里要判断不再初始化"""
        if getattr(SingleGod, '_inited') is True:
            return

        print('I am only God!')

    def __new__(cls, *args, **kwargs):
        """与具体类耦合,不够方便"""
        if not hasattr(cls, '_ins'):
            cls._ins = object.__new__(cls)
            cls._inited = False
        else:
            cls._inited = True
        return cls._ins


if __name__ == '__main__':
    God_1 = God()
    God_2 = God()

    print(God_1 is God_2)

    '''
    >>output
    I am only God!
    True
    '''
    God_3 = SingleGod()
    God_4 = SingleGod()

    print(God_3 is God_4)
    '''
    >>output
    I am only God!
    True
    '''

说明:单例模式绝对是众多设计模式中最常用的模式了,在平常的开发中经常会用到,比如由你实现一个数据库连接类,你一定不希望使用者在代码中到处创建数据库连接,而是调用统一创建的连接实例。依靠口头约束往往是不可靠的,一旦出现异常就会导致比较严重的生产事故,所以需要我们在设计之初就要做好限制。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值