简介
单例模式(singleton pattern),属于创建者模式的一种,主要用于面向对象编程中创建对象的一种模式。
单例类会负责创建自身的对象,并保证每次都是返回相同的对象。
本文博主通过常用的几种编程语言(JAVA、JS、Python)来实现各种单例模式。
应用场景
配置类: 当某个类需要提供系统相关配置,每次返回相同的实例。可以避免频繁的销毁创建配置类。
Java: J2EE 标 准 中 的 ServletContext 、 ServletContextConfig 等 、 Spring 框 架 应 用 中 的 ApplicationContext、数据库的连接池BDPool等也都是单例形式。Spring中Bean默认创建也是单例Bean,每个Ioc容器中只存在一个Bean的实例。
Python中的配置类,
线程池
实现方式
实现1:懒汉式 线程不安全
是否Lazy 初始化:是
是否线程安全: 否
最简单的单例模式实现方式。
/**
* Java编程语言
* 不支持多线程
*/
public class SingletonOne {
private static SingletonOne instance;
private SingletonOne(){}
public static SingletonOne getInstance() {
if (instance == null) {
instance = new SingletonOne();
}
return instance;
}
}
"""
Python编程语言
线程不安全
"""
class SimgleTonOne(object):
def __new__(cls, *args, **kwargs):
if not hasattr(SimgleTonOne, "_instance"):
setattr(SimgleTonOne, "_instance", object.__new__(SimgleTonOne))
return getattr(SimgleTonOne, "_instance")
/**
* 懒汉式
* @JS编程语言
* @param {*} name
*/
var SingletonOne = function (name) {
this.name = name;
}
SingletonOne.instance = null;
SingletonOne.prototype.getName = function () {
console.log(this.name)
}
SingletonOne.getInstance = function (name) {
if (!this.instance) {
this.instance = new SingletonOne(name);
}
return this.instance;
}
let a = SingletonOne.getInstance("xianren");
let b = SingletonOne.getInstance("xiaoliu");
console.log(a === b);
console.log(a.getName());
实现2:懒汉式 线程安全
/**
* Java
* 懒汉式单例
* 线程安全
*/
public class LazySimgleSafe {
private static LazySimgleSafe instance;
LazySimgleSafe(){ }
public static synchronized LazySimgleSafe getInstance() {
if(instance == null){
instance = new LazySimgleSafe();
}
return instance;
}
public static void main(String[] args) {
LazySimgleSafe lazySimgleSafe1 = LazySimgleSafe.getInstance();
LazySimgleSafe lazySimgleSafe2 = LazySimgleSafe.getInstance();
System.out.println(lazySimgleSafe1 == lazySimgleSafe2);
}
}
实现3:饿汉式
是否Lazy 初始化:否
是否线程安全: 是
最常用的单例模式实现方式。容易产生垃圾对象,类装载的时候就实例化
/**
* 饿汉式
* @Java编程语言
*/
public class SingletonTwo{
private static SingletonTwo instance = new SingletonTwo();
private SingletonTwo(){}
public static SingletonTwo getInstance() {
return instance;
}
}
"""
python编程语言
饿汉式
程序开始运行时实例化类
"""
# Simgletontwo.py
class Simgletontwo(object):
def __init__(self):
pass
S = Simgletontwo()
# test.py
from Simgletontwo import S
/**
JS语言
饿汉式单例
*/
var hungrySingleton = (function () {
var person = {
name: "张三"
}
return function () {
return {
getInfo: function () {
return person;
}
}
}
})();
var personA = hungrySingleton();
var personB = hungrySingleton();
var personC = hungrySingleton();
var infoA = personA.getInfo();
var infoB = personB.getInfo();
var infoC = personC.getInfo();
console.log(infoA);
console.log(infoB);
console.log(infoC);
console.log(infoA === infoB, infoB === infoC);
infoA.name = "李四";
console.log(infoA);
console.log(infoB);
console.log(infoC);
console.log(infoA === infoB, infoB === infoC);
后续继续更新...