当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 每天一个设计模式之单例模式

每天一个设计模式之单例模式

2018年11月02日  | 移动技术网IT编程  | 我要评论

博主按:《每天一个设计模式》旨在初步领会设计模式的精髓,目前采用javascript靠这吃饭)和python纯粹喜欢)两种语言实现。诚然,每种设计模式都有多种实现方式,但此小册只记录最直截了当的实现方式 :)

  1. 网速过慢的朋友请移步
  2. 欢迎来我的小站看更多干货 + 免费教程:

0. 项目地址

1. 什么是单例模式?

单例模式定义:保证一个类仅有一个实例,并提供访问此实例的全局访问点。

2. 单例模式用途

如果一个类负责连接数据库的线程池、日志记录逻辑等等,此时需要单例模式来保证对象不被重复创建,以达到降低开销的目的。

3. 代码实现

需要指明的是,以下实现的单例模式均为“惰性单例”:只有在用户需要的时候才会创建对象实例。

3.1 python3 实现

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))

3.2 javascript 实现

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);

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网