python一种用staticmethod实现单例模式方法的探讨
来源:互联网 发布:国内javascript现状 编辑:程序博客网 时间:2024/05/16 14:35
初步实现代码如下:
class Singleton(object): instance = None def __init__(self): pass @staticmethod def get_instance(): if Singleton.instance is None: Singleton.instance = Singleton() return Singleton.instancea = Singleton.get_instance()b = Singleton.get_instance()c = Singleton()print('a id=', id(a))print('b id=', id(b))
输出:
>>> a id= 39119224>>> b id= 39119224
class Singleton(object): instance = None def __init__(self): pass @staticmethod def get_instance(): if Singleton.instance is None: Singleton.instance = Singleton() return Singleton.instancea = Singleton.get_instance()b = Singleton.get_instance()c = Singleton()print('a id=', id(a))print('b id=', id(b))print('c id=', id(c))
输出:
>>> a id= 39119056>>> b id= 39119056>>> c id= 39117992c是通过类实例化的id和a、b的不一样。
有没有办法禁止通过类来实例化呢?我们可以在__init__中做文章,在__init__中抛出异常即可禁止实例化了,但是还是有问题,因为get_instance里面就是通过类来实例化的:
@staticmethod def get_instance(): if Singleton.instance is None: Singleton.instance = Singleton() return Singleton.instance
@staticmethod def get_instance(): if Singleton.instance is None: Singleton.instance = object.__new__(Singleton) return Singleton.instance
完整代码如下:
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.instancea = Singleton.get_instance()b = Singleton.get_instance()print('a id=', id(a))print('b id=', id(b))c = Singleton()print(id(c))
输出:
>>> Traceback (most recent call last): File "E:/Code/python3/otherTest/singleTest.py", line 18, in <module> c = Singleton() File "E:/Code/python3/otherTest/singleTest.py", line 5, in __init__ raise SyntaxError('can not instance, please use get_instance')SyntaxError: can not instance, please use get_instance>>> a id= 39184592>>> b id= 39184592
可以看出不能通过类实例化,只能通过get_instance函数获取实例。
PS:同样的通过classmethod也能实现单例模式,见python一种用classmethod实现单例模式方法的探讨。
阅读全文
1 0
- python一种用staticmethod实现单例模式方法的探讨
- python一种用classmethod实现单例模式方法的探讨
- 单例模式的一种实现方法
- 单例模式的一种实现方法
- python中7种实现单例模式的方法:staticmethod、classmethod、类属性方法、__new__、装饰器、元类、名字覆盖
- python3一个用类属性方法实现单例模式的探讨
- C++单例模式的一种实现
- 单例模式(4)- 一种更好的单例实现方法
- 一种单例的实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法:
- Python单例模式的4种实现方法
- Python单例模式的4种实现方法
- 控制执行流程
- H5新增标签
- Retrofit + RxJava + OkHttp 让网络请求变的简单-封装篇
- 洛谷 P1443 马的遍历
- 软raid5的挂载
- python一种用staticmethod实现单例模式方法的探讨
- Hive存储过程HQL/SQL(二)– 在Hive存储过程中读写MySQL表
- 第11章:Shell编程
- 三句话影响人的一生
- 文件节点写函数xxxx_store返回值
- xxx is not in the sudoers file. This incident will be reported解决方法
- 很强大的一个jquery分页插件
- RxJava + Retrofit完成网络请求
- Android开源库集合(工具)