博主按:《天天一个设计模式》旨在初步领会设计模式的精髓,目前采用
javascript
(靠这吃饭)和python
(纯粹喜欢)两种语言实现。诚然,每种设计模式都有多种实现方式,但此小册只记录最直截了当的实现方式 :)javascript
单例模式定义:保证一个类仅有一个实例,并提供访问此实例的全局访问点。java
若是一个类负责链接数据库的线程池、日志记录逻辑等等,此时须要单例模式来保证对象不被重复建立,以达到下降开销的目的。python
须要指明的是,如下实现的单例模式均为“惰性单例”:只有在用户须要的时候才会建立对象实例。git
class Singleton: # 将实例做为静态变量 __instance = None @staticmethod def get_instance(): if Singleton.__instance == None: # 若是没有初始化实例,则调用初始化函数 # 为Singleton生成 instance 实例 Singleton() return Singleton.__instance def __init__(self): if Singleton.__instance != None: raise Exception("请经过get_instance()得到实例") else: # 为Singleton生成 instance 实例 Singleton.__instance = self if __name__ == "__main__": s1 = Singleton.get_instance() s2 = Singleton.get_instance() # 查看内存地址是否相同 print(id(s1) == id(s2))
const Singleton = function() {}; Singleton.getInstance = (function() { // 因为es6没有静态类型,故闭包: 函数外部没法访问 instance let instance = null; return function() { // 检查是否存在实例 if (!instance) { instance = new Singleton(); } return instance; }; })(); let s1 = Singleton.getInstance(); let s2 = Singleton.getInstance(); console.log(s1 === s2);