Python进阶之:单例模式实现方法汇总

# -*- coding: utf-8 -*-
# @File  : 单例模式.py
# @Author: dianxiaoer
# @Date  : 2019/12/20
# @Desc  :

'''单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。
比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息。
如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,
而这样会严重浪费内存资源,尤其是在配置文件内容很多的情况下。事实上,类似 AppConfig 这样的类,我们希望在程序运行期间只存在一个实例对象。
'''
# 多种方式实现单例
# 1、使用模块
'''
其实,Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。
因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。如果我们真的想要一个单例类,可以考虑这样做
'''
# mysingleton.py

# class MySingleton(object):
#     def foo(self):
#         pass
#
# mysingleton = MySingleton()
#
# # 如何使用呢?将上面的代码保存在文件 mysingleton.py 中,然后这样使用:
#
# from mysingleton import MySingleton
#
# mysingleton.foo()

# 2、使用__new__
# 为了使类只能出现一个实例,我们可以使用 __new__ 来控制实例的创建过程,代码如下:

# class Singleton(object):
#     _instance = None
#     def __new__(cls, *args, **kwargs):
#         if not cls._instance:
#             cls._instance = super(Singleton,cls).__new__(cls, *args, **kwargs)
#         return cls._instance
#
# class MyClass(Singleton):
#     a = 1
# #在上面的代码中,我们将类的实例和一个类变量 _instance 关联起来,如果 cls._instance 为 None 则创建实例,
# #否则直接返回 cls._instance
#
# one = MyClass()
# two = MyClass()
#
# print(one is two)
# print(one == two)
#
# print(id(one),id(two))

# 3、使用装饰器
# 我们知道,装饰器(decorator)可以动态地修改一个类或函数的功能。
# 这里,我们也可以使用装饰器来装饰某个类,使其只能生成一个实例,代码如下:

# from functools import wraps
#
# def singleton(cls):
#     instances = {}
#     @wraps(cls)
#     def getinstance(*args,**kwargs):
#         if cls not in instances:
#             instances[cls] = cls(*args,**kwargs)
#         return instances[cls]
#     return getinstance
#
# @singleton
# class MyClass(object):
#     a = 1

# 在上面,我们定义了一个装饰器 singleton,它返回了一个内部函数 getinstance,
# 该函数会判断某个类是否在字典 instances 中,如果不存在,则会将 cls 作为 key,
# cls(*args, **kw) 作为 value 存到 instances 中,否则,直接返回 instances[cls]。

# 4、使用元类

# 元类(metaclass)可以控制类的创建过程,它主要做三件事:
#
# 拦截类的创建
# 修改类的定义
# 返回修改后的类
# 使用元类实现单例模式的代码如下:

# class SingletonMeta(type):
#     _instances = {}
#     def __call__(cls, *args, **kwargs):
#         if cls not in cls._instances:
#             cls._instances[cls] = super(SingletonMeta,cls).__call__(*args, **kwargs)
#         return cls._instances[cls]
#
# # Python2 写法
# # class MyClass(object):
# #     __metaclass = SingletonMeta
#
# # Python 3 写法
# class MyClass(SingletonMeta):
#     pass

# 元类除了使用__new__()和__init__()外,
# 所谓---还可以使用__call__()来拦截(使用元类的)类创建实例的过程

# 5、staticmethod

# class Singleton(object):
#     instance = None
#
#     def __init__(self):
#         raise SyntaxError("can not instance,please use get_instance")
#
#     @staticmethod
#     def get_instance():
#         if Singleton.instance is None:
#             Singleton.instance = object.__new__(Singleton)
#         return Singleton.instance
#
# a = Singleton.get_instance()
# b = Singleton.get_instance()
# print(id(a),id(b))

# 该方法的要点是在__init__抛出异常,禁止通过类来实例化,
# 只能通过静态get_instance函数来获取实例;因为不能通过类来实例化,
# 所以静态get_instance函数中可以通过父类object.__new__来实例化

# 6、classmethod
# 类比静态方法

# class Singleton(object):
#     instance = None
#
#     def __init__(self):
#         raise SyntaxError("can not instance,please use get_instance")
#
#     @classmethod
#     def get_instance(cls):
#         if Singleton.instance is None:
#             Singleton.instance = object.__new__(Singleton)
#         return Singleton.instance
#
#
# a = Singleton.get_instance()
# b = Singleton.get_instance()
# print(id(a), id(b))

# 该方法的要点是在__init__抛出异常,禁止通过类来实例化,
# 只能通过静态get_instance函数来获取实例;因为不能通过类来实例化,
# 所以静态get_instance函数中可以通过父类object.__new__来实例化。

# 7、类属性方法

# class Singleton(object):
#     instance = None
#
#     def __init__(self):
#         raise SyntaxError("can not instance,please use get_instance")
#
#     def get_instance():
#         if Singleton.instance is None:
#             Singleton.instance = object.__new__(Singleton)
#         return Singleton.instance
#
#
# a = Singleton.get_instance()
# b = Singleton.get_instance()
# print(id(a), id(b))

# 该方法的要点是在__init__抛出异常,禁止通过类来实例化,只能通过静态get_instance函数来获取实例;
# 因为不能通过类来实例化,所以静态get_instance函数中可以通过父类object.__new__来实例化。
# 个人觉得这个代码有点小问题???【20191220注释】

# 8、名字覆盖

# class Singleton(object):
#     def foo(self):
#         print('foo')
#     def __call__(self):
#         return self
#
# singleton = Singleton()
# singleton.foo()
#
# a = Singleton()
# b = Singleton()
# print(id(a),id(b))

# 代码不太协调

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值