单例模式各种代码实现
程序员文章站
2022-07-13 23:40:14
...
单例主要分两种,懒汉式和饿汉式。饿汉式就是当类装载的时候就会创建类实例,不管你用不用,先把对象创建出来。懒汉式就是延迟加载,对象一开始并不会创建出来,而是每次获取实例都会进行判断,看是否需要创建实例。
饿汉式
class Demo{
private static Demo demo = new Demo();
private Demo() {}
public static Demo getInstance() {
return demo;
}
}
懒汉式单线程
class Demo{
private static Demo demo;
private Demo() {}
public static Demo getInstance() {
if(demo == null) {
demo = new Demo();
}
return demo;
}
}
懒汉式多线程(效率很低)
class Demo{
private static Demo demo;
private Demo() {}
public static synchronized Demo getInstance() {
if(demo == null) {
demo = new Demo();
}
return demo;
}
}
懒汉式多线程双检锁
class Demo{
private static volatile Demo demo;
private Demo() {}
public static Demo getInstance() {
if(demo == null) {
synchronized (Demo.class) {
if(demo == null) {
demo = new Demo();
}
}
}
return demo;
}
}
懒汉式多线程静态内部类实现
class Demo{
private Demo() {}
private static final class InnerClass{
private static Demo demo = new Demo();
}
public static Demo getInstance() {
return InnerClass.demo;
}
}
上一篇: Python单例模式的各种姿势
下一篇: 2021-07-05