<人人都懂设计模式>-单例模式
这个模式,我还是了解的。
书上用了三种不同的方法。
class Singleton1:
# 单例实现方式1
__instance = None
__is_first_init = False
def __new__(cls, name):
if not cls.__instance:
Singleton1.__instance = super().__new__(cls)
return cls.__instance
def __init__(self, name):
if not self.__is_first_init:
self.__name = name
self.__is_first_init = True
def get_name(self):
return self.__name
tony = Singleton1('Tony')
karry = Singleton1('karry')
print(tony.get_name(), karry.get_name())
print(id(tony), id(karry))
print(tony == karry)
print("=======单例实现方式1========")
class Singleton2(type):
# 单例实现方式2
def __init__(cls, what, bases=None, dict=None):
super().__init__(what, bases, dict)
cls._instance = None
def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
class CustomClass(metaclass=Singleton2):
def __init__(self, name):
self.__name = name
def get_name(self):
return self.__name
tony = CustomClass('Tony')
karry = CustomClass('karry')
print(tony.get_name(), karry.get_name())
print(id(tony), id(karry))
print(tony == karry)
print("=======单例实现方式2========")
def singleton_decorator(cls, *args, **kwargs):
instance = {}
def wrapper_singleton(*args, **kwargs):
if cls not in instance:
instance[cls] = cls(*args, **kwargs)
return instance[cls]
return wrapper_singleton
@singleton_decorator
class Singleton3:
# 单例实现方式2
def __init__(self, name):
self.__name = name
def get_name(self):
return self.__name
tony = Singleton3('Tony')
karry = Singleton3('karry')
print(tony.get_name(), karry.get_name())
print(id(tony), id(karry))
print(tony == karry)
print("=======单例实现方式3========")
C:\Python36\python.exe C:/Users/Sahara/PycharmProjects/test1/test.py Tony Tony 39257648 39257648 True =======单例实现方式1======== Tony Tony 39257984 39257984 True =======单例实现方式2======== Tony Tony 39257928 39257928 True =======单例实现方式3======== Process finished with exit code 0
<人人都懂设计模式>-单例模式的更多相关文章
- <人人都懂设计模式>-装饰模式
书上,真的用一个人穿衣打拌来讲解装饰模式的呢. from abc import ABCMeta, abstractmethod class Person(metaclass=ABCMeta): def ...
- <人人都懂设计模式>-中介模式
真正的用房屋中介来作例子, 好的书籍总是让人记忆深刻. class HouseInfo: def __init__(self, area, price, has_window, has_bathroo ...
- <人人都懂设计模式>-状态模式
同样是水,固态,气态,液态的变化,是由温度引起. 引此为思考状态模式. from abc import ABCMeta, abstractmethod # 引入ABCMeta和abstractmeth ...
- 人人都懂区块链--pdf电子版学习资料下载
人人都懂区块链 21天从区块链“小白”到资深玩家电子版pdf下载 链接:https://pan.baidu.com/s/1TWxYv4TLa2UtTgU-HqLECQ 提取码:6gy0 好的学习资料需 ...
- 【人人都懂密码学】一篇最易懂的Java密码学入门教程
密码与我们的生活息息相关,远到国家机密,近到个人账户,我们每天都在跟密码打交道: 那么,密码从何而来?生活中常见的加密是怎么实现的?怎么保证个人信息安全?本文将从这几方面进行浅谈,如有纰漏,敬请各位大 ...
- 人人都懂的HTML基础知识-HTML教程(1)
01.HTML基础简介 HTML (HyperText Markup Language,超文本标记语言) 不是一门编程语言,而是一种用于定义内容结构的标记语言,用来描述网页内容,文件格式为.html. ...
- JavaScript设计模式-单例模式、模块模式(转载 学习中。。。。)
(转载地址:http://technicolor.iteye.com/blog/1409656) 之前在<JavaScript小特性-面向对象>里面介绍过JavaScript面向对象的特性 ...
- 设计模式 单例模式(Singleton) [ 转载2 ]
设计模式 单例模式(Singleton) [ 转载2 ] @author java_my_life 单例模式的结构 单例模式的特点: 单例类只能有一个实例. 单例类必须自己创建自己的唯一实例. 单例类 ...
- 设计模式 单例模式(Singleton) [ 转载 ]
设计模式 单例模式(Singleton) [ 转载 ] 转载请注明出处:http://cantellow.iteye.com/blog/838473 前言 懒汉:调用时才创建对象 饿汉:类初始化时就创 ...
随机推荐
- you have new mail in /var/spool/mail/root !
今天开发的同事告诉我,他在登录系统时老是提示you have new mail in /var/spool/mail/root ! 我一猜就知道他们肯定又自己写定时任务了,这样的事已经发生过好几回了, ...
- [C2P1] Andrew Ng - Machine Learning
About this Course Machine learning is the science of getting computers to act without being explicit ...
- LeetCode 674. Longest Continuous Increasing Subsequence最长连续递增序列 (C++/Java)
题目: Given an unsorted array of integers, find the length of longest continuous increasing subsequenc ...
- 设计模式-抽象工厂模式(AbstractFactory)(创建型模式)
//以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码 //Product.h #pragma once class AbstractProductA { public: vir ...
- c++负数下标
如何使用负数下标呢? 让数组前面有东西 int y[100]; int *z = y + 50; 这样的话调用\(z[-50]\)就变成了调用\(y[0]\) z[-50] = y[0]; 然后这样就 ...
- bootstrap-editable 中关于onEditableSave 回调
问题描述 在对bootstrap-editable 进行编辑时,有两种使用方法:一种直接在每一个column中进行编辑保存,例如:{ title:'标题', field:'title', width: ...
- git push时出现 Username for 'https://github.com': 仅仅限于github
使用git push origin master是出现如下问题:Username for 'https://github.com': 解决办法: git remote set-url origin g ...
- Centos7安装percona-xtrabackup2.4和8.0版本
Percona XtraBackup是一个基于MySQL的服务器的开源热备份实用程序 ,它不会在备份期间锁定您的数据库.无论是24x7高负载服务器还是低事务量环境,Percona XtraBackup ...
- Practical Go: Real world advice for writing maintainable Go programs
转自:https://dave.cheney.net/practical-go/presentations/qcon-china.html?from=timeline 1. Guiding pri ...
- Winform中设置ZedGraph的曲线为散点图
场景 Winform中设置ZedGraph的曲线符号Symbol以及对应关系: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/10 ...